class SearchController(BaseController): @check_perm('search.do') def index(self): """Form for full-text search.""" c.form = FormGenerator() c.form.defaults['perpage'] = int(pylons.config.get('gallery.default_perpage',12)) return render('search/index.mako') @check_perm('search.do') def do(self): """Form handler for full-text search.""" # ... yeah. Stubbed for now. validator = model.form.SearchForm() try: c.search_terms = validator.to_python(request.params) except formencode.Invalid, error: c.form = FormGenerator(form_error=error) return render('search/index.mako') c.form = FormGenerator() c.form.defaults = c.search_terms abort(400);
def login_check(self): """User login POST target.""" if c.auth_user: # This shouldn't really happen, so no need to be nice about it h.redirect_to('/') username = request.params.get('username', '') user_q = model.Session.query(model.User) user = user_q.filter_by(username=username).first() c.form = FormGenerator() if user and user.check_password(request.params.get('password')): if not user.can('index.login'): c.error_msgs.append( "This account (%s) still needs to be verified. " \ "Please check the email address provided for the " \ "verification code." % h.html_escape(username) ) c.form.defaults['username'] = username return render('/login.mako') else: session['user_id'] = user.id session.save() h.redirect_to(request.headers.get('referer', '/')) else: c.error_msgs.append( "Either there is no such account '%s', or the provided " \ "password was incorrect." % h.html_escape(username) ) c.form.defaults['username'] = username return render('/login.mako')
def auth_verify(self): """User login POST target.""" username = request.params.get('username', '') user_q = model.Session.query(model.User) user = user_q.filter_by(username=username).first() c.form = FormGenerator() if user and user.check_password(request.params.get('password')): if not user.can('index.login'): c.error_msgs.append( "This account (%s) still needs to be verified. " \ "Please check the email address provided for the " \ "verification code." % h.html_escape(username) ) c.form.defaults['username'] = username return render('/login.mako') else: session['user_id'] = user.id if user.can('admin.auth'): session['admin_last_used'] = int(time.time()) else: session['admin_last_used'] = 0 session.save() h.redirect_to(h.url_for(controller='admin', action='index')) else: c.error_msgs.append( "Either there is no such account '%s', or the provided " \ "password was incorrect." % h.html_escape(username) ) c.form.defaults['username'] = username return render('/login.mako')
def relationships(self, username=None, sub_domain=None): """Edit user's relationships""" c.user = model.User.get_by_name(username) if not c.user: abort(404) fetch_relationships() c.form = FormGenerator() if 'other_user' in request.params \ and request.params['other_user'] != c.user.username: c.other_user = model.User.get_by_name(request.params['other_user']) # other_user indicates we are trying to add somebody if c.other_user: if c.other_user in c.relationship_order: c.relationship_order.remove(c.other_user) c.relationship_order.insert(0, c.other_user) # If we're editing someone specifically, they might not have their # key in the relationships dictionary yet. if not c.other_user in c.relationships.keys(): c.relationships[c.other_user] = [] # If they asked for a relationship, make sure it defaults to on if 'relationship' in request.params: rel = request.params['relationship'] if rel not in c.relationships[c.other_user]: c.relationships[c.other_user].append(rel) return render('user/settings/relationships.mako')
def write_send(self, username): """Form handler for sending any note.""" validator = model.form.SendNoteForm() try: form_data = validator.to_python(request.params) except formencode.Invalid, error: c.form = FormGenerator(form_error=error) return render('notes/send.mako')
def login(self): """User login form.""" if c.auth_user: # This shouldn't really happen, so no need to be nice about it h.redirect_to('/') c.form = FormGenerator() return render('/login.mako')
def register_check(self): """User registration POST target.""" schema = model.form.RegisterForm() try: form_data = schema.to_python(request.params) except formencode.Invalid, error: c.form = FormGenerator(form_error=error) return render('/register.mako')
def __before__(self, action, **params): # This is done as a closure so it can just be called from the footer # in the template, putting off the final time() as late as possible start_time = time() def time_elapsed(): return time() - start_time c.time_elapsed = time_elapsed c.query_log = QueryLog() c.config = Config().readdb(model.Config) c.empty_form = FormGenerator() c.error_msgs = [] c.route = request_config().mapper_dict c.javascripts = ['jquery-1.2.6.pack', 'common'] c.site_name = config.get('site_name', 'Ferrox') if 'user_id' in session: try: user_id = session['user_id'] c.auth_user = model.Session.query(model.User) \ .options(eagerload('active_bans')) \ .get(user_id) except InvalidRequestError: # User may have been deleted in the interim del session['user_id'] session.save() if c.auth_user: ip = request.environ['REMOTE_ADDR'] ip = inet.pton(ip) if c.auth_user.can('admin.auth'): session['admin_ip'] = ip cip = inet.ntop(ip) # Log IPs ip_log_q = model.Session.query(model.IPLogEntry) last_ip_record = ip_log_q.filter_by(user_id = user_id) \ .order_by(model.IPLogEntry.end_time.desc()).first() if last_ip_record and last_ip_record.ip == cip: last_ip_record.end_time = datetime.now() else: model.Session.add(model.IPLogEntry(user_id, ip)) # Check to see if there are any active bans to expire if c.auth_user.active_bans: for ban in c.auth_user.active_bans: if ban.expires <= datetime.now(): ban.expired = True c.auth_user.role = ban.revert_to # Magical commit. model.Session.commit() else: c.auth_user = model.GuestUser()
def edit_commit(self, id): """Form handler for editing news.""" c.item = model.Session.query(model.News).get(id) schema = model.form.NewsForm() try: form_data = schema.to_python(request.params) except formencode.Invalid, error: c.form = FormGenerator(form_error=error) return render('news/edit.mako')
def forward(self, username, id): """Form for forwarding a note.""" self._note_setup(username, id) c.form = FormGenerator() c.form.defaults['subject'] = 'Fwd: ' + c.note.base_subject() c.form.defaults['content'] = "[quote=%s]%s[/quote]\n" % \ (c.note.sender.username, c.note.content) return render('notes/send.mako')
def edit_commit(self, id=None): """Form handler for editing a journal entry.""" # -- validate form input -- validator = model.form.JournalForm() try: form_data = validator.to_python(request.params) except formencode.Invalid, error: c.is_edit = True c.form = FormGenerator(form_error=error) return render('/journal/post.mako')
def submit_upload(self): """Form handler for uploading new art.""" validator = model.form.SubmitForm() try: form_data = validator.to_python(request.params) except formencode.Invalid, error: c.edit = False c.form = FormGenerator(form_error=error) return render('/gallery/submit.mako')
def do_post(self): """Form handler for posting news.""" c.form = FormGenerator() schema = model.form.NewsForm() try: form_data = schema.to_python(request.params) except formencode.Invalid, error: c.form.defaults = error.value c.form.errors = error.error_dict return render('news/post.mako')
def do(self): """Form handler for full-text search.""" # ... yeah. Stubbed for now. validator = model.form.SearchForm() try: c.search_terms = validator.to_python(request.params) except formencode.Invalid, error: c.form = FormGenerator(form_error=error) return render('search/index.mako')
def register(self): """User registration.""" c.form = FormGenerator() c.form.defaults = { 'username': '', 'email': '', 'email_confirm': '', 'password': '', 'password_confirm': '' } return render('/register.mako')
def edit(self, id=None): """Form for editing a journal entry.""" journal_entry = get_journal(id) self.is_my_journal(journal_entry, True) c.is_edit = True c.form = FormGenerator() c.form.defaults['title'] = journal_entry.title c.form.defaults['content'] = journal_entry.content c.entry = journal_entry return render('/journal/post.mako')
def reply(self, post_url, id=None): """Post a comment, either top-level or replying to another comment.""" post = self._get_parent_post(post_url) c.form = FormGenerator() if id: c.comment = model.Session.query(model.Comment).get(id) if c.comment.discussion != post.discussion: abort(404) else: c.comment = None return render('comments/reply.mako')
def delete(self, id=None, username=None): """Form for deleting a submission.""" c.submission = get_submission(id) c.form = FormGenerator() c.target_user = model.User.get_by_name(username) self._check_target_user() c.text = "Are you sure you want to delete the submission \"%s\"?" % \ c.submission.title c.url = h.url_for(controller='gallery', action="delete_commit", id=id, username=username) c.fields = {} return render('/gallery/delete.mako')
def reply(self, username, id): """Form for replying to a note.""" self._note_setup(username, id) c.reply_to_note = c.note.latest_note(c.page_owner) c.form = FormGenerator() c.form.defaults['subject'] = 'Re: ' + c.note.base_subject() c.form.defaults['content'] = "[quote=%s]%s[/quote]\n" % \ (c.note.sender.username, c.note.content) if c.reply_to_note.recipient == c.page_owner: c.recipient = c.reply_to_note.sender else: c.recipient = c.reply_to_note.recipient c.form.defaults['reply_to_note'] = c.reply_to_note.id return render('notes/send.mako')
def reply_commit(self, post_url, id=None): """Form handler for reply to a comment.""" post = self._get_parent_post(post_url) if id: c.parent = model.Session.query(model.Comment).get(id) if c.parent.discussion != post.discussion: abort(404) else: c.parent = None validator = model.form.CommentForm() try: form_data = validator.to_python(request.params) except formencode.Invalid, error: c.form = FormGenerator(form_error=error) return render('comments/reply.mako')
def edit(self, id=None, username=None): """Form for editing a submission.""" c.submission = get_submission(id, ['tags']) c.target_user = model.User.get_by_name(username) self._check_target_user() c.edit = True c.form = FormGenerator() c.form.defaults['title'] = c.submission.title c.form.defaults['description'] = c.submission.get_user_submission( c.target_user).content #tag_list = tagging.TagList() #tag_list.parse_tag_object_array(submission.tags, negative=False) c.form.defaults['tags'] = tagging.make_tag_string(c.submission.tags) return render('/gallery/submit.mako')
def _generic_gallery(self, joined_tables=None, where_clauses=[]): """Generic backend for viewing a gallery. Handles default tag filtering, as well as a set of default controls like further filtering, sorting, and pagination. Pass a pre-joined `joined_tables` sqla.sql object to filter further before this method does its mucking around.""" # Some defaults if not joined_tables: joined_tables = model.Submission.__table__ \ .join(model.UserSubmission.__table__) # Form validation validator = model.form.TagFilterForm() try: form_data = validator.to_python(request.params) except formencode.Invalid, error: c.form = FormGenerator(form_error=error) return render('gallery/index.mako')
def edit_commit(self, id=None, username=None): """Form handler for editing a submission.""" # -- get image from database, make sure user has permission -- # Error handling needs submission, so we need to get it no matter what. c.submission = get_submission(id, [ 'tags', 'user_submissions', 'user_submissions.user', 'user_submissions.editlog', 'user_submissions.editlog.entries' ]) c.target_user = model.User.get_by_name(username) self._check_target_user() user_submission = c.submission.get_user_submission(c.target_user) # -- validate form input -- validator = model.form.EditForm() form_data = None try: form_data = validator.to_python(request.params) except formencode.Invalid, error: c.edit = True c.form = FormGenerator(form_error=error) return render('/gallery/submit.mako')
def post(self): """Form for posting a journal entry.""" c.form = FormGenerator() c.is_edit = False return render('/journal/post.mako')
def submit(self): """Form for uploading new art.""" c.edit = False c.form = FormGenerator() return render('/gallery/submit.mako')
class GalleryController(BaseController): def _generic_gallery(self, joined_tables=None, where_clauses=[]): """Generic backend for viewing a gallery. Handles default tag filtering, as well as a set of default controls like further filtering, sorting, and pagination. Pass a pre-joined `joined_tables` sqla.sql object to filter further before this method does its mucking around.""" # Some defaults if not joined_tables: joined_tables = model.Submission.__table__ \ .join(model.UserSubmission.__table__) # Form validation validator = model.form.TagFilterForm() try: form_data = validator.to_python(request.params) except formencode.Invalid, error: c.form = FormGenerator(form_error=error) return render('gallery/index.mako') c.form = FormGenerator() ### SQL # Some defaults.. # XXX admins can see more than this where_clauses.append(model.UserSubmission.deletion_id == None) ### Tag filtering # Construct a list of required and excluded tags required_tags = [] excluded_tags = [] invalid_tags = [] (required_tag_names, excluded_tag_names) \ = tagging.break_apart_tag_string(form_data['tags'], include_negative=True) for tag_list, tag_name_list in (required_tags, required_tag_names), \ (excluded_tags, excluded_tag_names): for tag_name in tag_name_list: tag = model.Tag.get_by_text(tag_name) if tag: tag_list.append(tag) else: invalid_tags.append(tag_name) # Error on invalid tags if invalid_tags: c.form.errors['tags'] = 'No such tags: ' + ', '.join(invalid_tags) return render('gallery/index.mako') # Require tags via simple INNER JOINs for tag in required_tags: alias = model.SubmissionTag.__table__.alias() joined_tables = joined_tables.join( alias, and_( model.Submission.id == alias.c.submission_id, alias.c.tag_id == tag.id, )) # Exclude tags via LEFT JOIN .. WHERE IS NULL excluded_aliases = [] for tag in excluded_tags: alias = model.SubmissionTag.__table__.alias() joined_tables = joined_tables.outerjoin( alias, and_( model.Submission.id == alias.c.submission_id, alias.c.tag_id == tag.id, )) where_clauses.append(alias.c.tag_id == None) # Pagination pageno = form_data['page'] or 1 perpage = form_data['perpage'] or \ pylons.config.get('gallery.default_perpage', 12) c.form.defaults['perpage'] = perpage try: (c.submissions, submission_ct) = find_submissions( joined_tables=joined_tables, where_clauses=where_clauses, tag_string=form_data['tags'], page_num=pageno, page_size=perpage, ) except NoSuchTagsException, e: c.form.errors['tags'] = 'No such tags: ' + ', '.join(e.tags) return render('gallery/index.mako')
def index(self): """Form for full-text search.""" c.form = FormGenerator() c.form.defaults['perpage'] = int(pylons.config.get('gallery.default_perpage',12)) return render('search/index.mako')
def edit(self): """Form for editing news.""" c.form = FormGenerator() c.item = model.Session.query(model.News).get(c.id) c.form.defaults = h.to_dict(c.item) return render('news/edit.mako')
def index(self, username=None, month=None, year=None, day=None, watchstream=False): """Journal index for a user.""" if username: user_q = model.Session.query(model.User) try: c.page_owner = user_q.filter_by(username=username).one() except sqlalchemy.exceptions.InvalidRequestError: c.error_text = "User %s not found." % h.html_escape(username) c.error_title = 'User not found' abort(404) else: c.page_owner = None c.page_link_dict = dict(controller='journal', action='index') if c.page_owner: c.page_link_dict['username'] = c.page_owner.username if year and month and day: today = earliest = date(int(year), int(month), int(day)) latest = earliest + timedelta(days=1) c.page_link_dict.update({'year': year, 'month': month, 'day': day}) elif month and year: today = earliest = date(int(year), int(month), 1) latest = date(earliest.year + (earliest.month / 12), (earliest.month + 1) % 12, 1) c.page_link_dict.update({'year': year, 'month': month}) elif year: today = earliest = date(int(year), 1, 1) latest = date(earliest.year + 1, earliest.month, earliest.day) c.page_link_dict.update({'year': year}) else: today = latest = (date.today() + timedelta(days=1)) earliest = date(1970, 1, 1) max_per_page = int(pylons.config.get('journal.default_perpage', 20)) pageno = int(request.params.get('page', 1)) - 1 journal_q = model.Session.query(model.JournalEntry) \ .filter_by(status = 'normal') \ .filter(model.JournalEntry.time >= earliest) \ .filter(model.JournalEntry.time < latest) if c.page_owner and not watchstream: journal_q = journal_q.filter_by(user_id=c.page_owner.id) # ... grab c.page_owner's relationships and add them to the where clause if watchstream: watchstream_where = [] for r in c.page_owner.relationships: if 'watching_journals' in r.relationship: watchstream_where.append( model.UserSubmission.user_id == r.to_user_id) if watchstream_where: journal_q = journal_q.filter(or_(*watchstream_where)) else: # This means that c.page_owner isn't watching anyone. # We don't even need to bother querying. c.error_text = 'No journals found.' c.error_title = "No journals found. User '%s' isn't watching anyone." % c.page_owner.display_name return render('/error.mako') journal_q = journal_q.order_by(model.JournalEntry.time.desc()) c.journals = journal_q.limit(max_per_page).offset(pageno * max_per_page).all() num_journals = journal_q.count() c.title_only = False c.is_mine = c.page_owner and (c.auth_user and (c.page_owner.id == c.auth_user.id)) paging_radius = int(pylons.config.get('paging.radius', 3)) c.paging_links = pagination.populate_paging_links( pageno=pageno, num_pages=int(math.ceil(float(num_journals) / float(max_per_page))), perpage=max_per_page, radius=paging_radius) c.form = FormGenerator() c.by_date_base = dict(controller='journal', action='index') if c.page_owner: c.by_date_base['username'] = c.page_owner.username c.next_year = c.by_date_base.copy() c.next_year['year'] = today.year + 1 c.last_year = c.by_date_base.copy() c.last_year['year'] = today.year - 1 c.next_month = c.by_date_base.copy() c.next_month['month'] = today.month + 1 c.next_month['year'] = today.year if c.next_month['month'] > 12: c.next_month['month'] -= 12 c.next_month['year'] += 1 c.last_month = c.by_date_base.copy() c.last_month['month'] = today.month - 1 c.last_month['year'] = today.year if c.last_month['month'] < 1: c.last_month['month'] += 12 c.last_month['year'] -= 1 c.tomorrow = c.by_date_base.copy() tomorrow = today + timedelta(days=1) c.tomorrow['year'] = tomorrow.year c.tomorrow['month'] = tomorrow.month c.tomorrow['day'] = tomorrow.day c.yesterday = c.by_date_base.copy() yesterday = today - timedelta(days=1) c.yesterday['year'] = yesterday.year c.yesterday['month'] = yesterday.month c.yesterday['day'] = yesterday.day c.year, c.month, c.day = year, month, day c.today = date.today() if month and year: c.days_this_month = max([ x for x in calendar.Calendar().itermonthdays( int(year), int(month)) ]) return render('/journal/index.mako')
def post(self): """Form for posting news.""" c.form = FormGenerator() return render('news/post.mako')