def external_handler(request): "This allows for external login" from django.contrib.auth import authenticate, login url = "/show/mytags/" try: user = request.user get = request.GET.get form = formdef.ExternalLogin(request.GET) if form.is_valid(): data = form.cleaned_data['data'] if user.is_authenticated(): messages.info(request, "User <b>%s</b> session is active." % user.profile.display_name) else: user = authorize_external_user(request=request, data=data) messages.info(request, "User <b>%s</b> logged in" % user.profile.display_name) if form.cleaned_data.get('action') == "new": params = urllib.urlencode(request.GET.items()) url = "%s?%s" % (reverse("new-post"), params) return html.redirect(url) else: messages.error(request, "Invalid form data for external login %s" % form.errors) return html.redirect(url) except Exception, exc: messages.error(request, "Error on external login: %s" % exc) return html.redirect(url)
def post_show(request, pid): """ Displays a post and its children """ user = request.user # populate the session data sess = middleware.Session(request) tab = "posts" pill = sess.get_tab() auth = user.is_authenticated() layout = settings.USER_PILL_BAR if auth else settings.ANON_PILL_BAR params = html.Params(tab=tab, pill=pill, layout=layout) query = get_post_manager(request) try: root = query.get(id=pid) if not root.top_level: return html.redirect(root.get_absolute_url()) # update the views for the question models.update_post_views(post=root, request=request) counts = sess.get_counts() except models.Post.DoesNotExist, exc: messages.warning( request, 'The post that you are looking for does not exists. Perhaps it was deleted!' ) return html.redirect("/")
def post_show(request, pid): """ Displays a post and its children """ user = request.user # populate the session data sess = middleware.Session(request) tab = "posts" pill = sess.get_tab() auth = user.is_authenticated() layout = settings.USER_PILL_BAR if auth else settings.ANON_PILL_BAR params = html.Params(tab=tab, pill=pill, layout=layout) query = get_post_manager(request) try: root = query.get(id=pid) if not root.top_level: return html.redirect( root.get_absolute_url() ) # update the views for the question models.update_post_views(post=root, request=request, minutes=const.POST_VIEW_UPDATE) counts = sess.get_counts() except models.Post.DoesNotExist, exc: messages.warning(request, 'The post that you are looking for does not exists. Perhaps it was deleted!') return html.redirect("/")
def user_edit(request, uid): "User's profile page" user = models.User.objects.select_related('profile').get(id=uid) if not user.profile.editable(request.user): messages.error(request, "unable to edit this user") return html.redirect("/user/show/%s/" % uid) if request.method == 'GET': initial = dict( display_name = user.profile.display_name, email = user.email or '', location = user.profile.location or '', website = user.profile.website or '', about_me = user.profile.about_me or '' ) form = UserForm(initial) return html.template(request, name='user.edit.html', user=user, form=form) elif request.method == 'POST': form = UserForm(request.POST) if not form.is_valid(): return html.template(request, name='user.edit.html', user=user, form=form) else: for field in "display_name about_me website location".split(): setattr(user.profile, field, form.cleaned_data[field]) user.email = form.cleaned_data['email'] user.profile.save() user.save() return html.redirect("/user/show/%s/" % user.id)
def redirect_post(request, pid): try: nid = REMAP[pid] post = models.Post.objects.get(id=nid) return html.redirect(post.get_absolute_url(), permanent=True) except Exception, exc: messages.error(request, "Unable to redirect: %s" % exc) return html.redirect("/")
def linkout(request, pid): "Used to be able to count the views for a linkout" post = models.Post.objects.get(id=pid) models.update_post_views(post=post, request=request) post.set_rank() post.save() if post.url: return html.redirect(post.url) else: message.error(request, 'linkout used on a post with no url set %s' % post.id) return html.redirect("/")
def linkout(request, pid): "Used to be able to count the views for a linkout" post = models.Post.objects.get(id=pid) models.update_post_views(post=post, request=request) post.set_rank() post.save() if post.url: return html.redirect(post.url) else: messages.error(request, 'linkout used on a post with no url set %s' % post.id) return html.redirect("/")
def post_moderate(request, pid, status): "General moderation function" user = request.user post = models.Post.objects.get(id=pid) # remap the status to valid status = dict(close=POST_CLOSED, open=POST_OPEN, delete=POST_DELETED).get(status) if not status: messages.error('Invalid post moderation action') return html.redirect( post.get_absolute_url() ) url = models.post_moderate(request=request, user=user, post=post, status=status) return html.redirect( url )
def request_info(request, pid): "Requests information from a source" user = request.user post = models.Post.objects.get(id=pid) params = html.Params(site_domain = settings.SITE_DOMAIN, user=user, post=post) params.subject = "Your expert advice is needed at Biostar" if user.is_authenticated(): params.display_name, score = user.profile.display_name, user.profile.score else: params.display_name, score = "Anonymous", 0 params.body = html.fill(name='pages/request-info.txt', params=params) LIMIT = 5 disabled = score < LIMIT if disabled: messages.error(request, "Note: users with fewer than %s reputation points may not send messages via Biostar. You have %s points" % (LIMIT, score)) elif 'submit' in request.POST: form = formdef.RequestInfo(request.POST) if form.is_valid(): send_mail(subject=params.subject, from_email=settings.DEFAULT_FROM_EMAIL, message=params.body, recipient_list=[settings.DEFAULT_FROM_EMAIL, form.cleaned_data['email']], fail_silently=False) messages.info(request, "Your message has been sent.") return html.redirect( post.get_absolute_url() ) else: messages.error(request, "%s" % form.errors) return html.template(request, name='pages/request-info.html', params=params)
def post_show(request, pid): "Returns a question with all answers" user = request.user # populate the session data sess = middleware.Session(request) tab = "posts" pill = sess.get_tab() auth = user.is_authenticated() layout = settings.USER_PILL_BAR if auth else settings.ANON_PILL_BAR params = html.Params(tab=tab, pill=pill, layout=layout) query = get_post_manager(request) try: root = query.get(id=pid) # update the views for the question models.update_post_views(post=root, request=request, minutes=const.POST_VIEW_UPDATE) counts = sess.get_counts() except models.Post.DoesNotExist, exc: messages.warning( request, 'The post that you are looking for does not exists. Perhaps it was deleted!' ) return html.redirect("/")
def user_moderate(request, uid, status): "General moderation function" user = request.user target = models.User.objects.get(id=uid) url = target.profile.get_absolute_url() # remap the status to valid status = dict(suspend=USER_SUSPENDED, reinstate=USER_ACTIVE, ban=USER_BANNED).get(status) if not status: messages.error('Invalid user moderation action') return html.redirect( url ) flag, msg = models.user_moderate(user=user, target=target, status=status) func = messages.info if flag else messages.error func(request, msg) return html.redirect( url )
def private_message(request, uid): "General moderation function" user = request.user target = models.User.objects.get(id=uid) # TODO allow users to opt out from getting messages # get the message from the body text = request.POST.get("message","").strip()[:1500] text = html.generate(text) text = html.sanitize(text) if not text: messages.error(request, 'Empty message') else: content = "PM to %s: %s" % (notegen.userlink(target), text) models.send_note(target=user, content=content, sender=user, both=False, unread=False, type=NOTE_PRIVATE, url=user.profile.get_absolute_url() ) content = "PM from %s: %s" % (notegen.userlink(user), text) models.send_note(target=target, content=content, sender=user, both=False, type=NOTE_PRIVATE, url=user.profile.get_absolute_url() ) tasks.send_test_email() messages.info(request, 'Your private message to <b>%s</b> has been sent!' % target.profile.display_name) return html.redirect( target.profile.get_absolute_url() )
def request_merge(request): "Generates an account merge request" class MergeForm(forms.Form): "A form representing a new question" master_id = forms.CharField(max_length=5, initial="", widget=forms.TextInput(attrs={'size':'5'})) remove_id = forms.CharField(max_length=5, initial="", widget=forms.TextInput(attrs={'size':'5'})) user = request.user if request.method == 'POST': form = MergeForm(request.POST) if form.is_valid(): try: data = form.cleaned_data master = models.User.objects.get(id=data['master_id']) remove = models.User.objects.get(id=data['remove_id']) fill = dict( domain=settings.SITE_DOMAIN, master_id=master.id, remove_id=remove.id, master_name = master.profile.display_name, remove_name=remove.profile.display_name, master_email = master.email, remove_email=remove.email, request_id = request.user.id, request_name = user.profile.display_name, ) body = ACCOUNT_MERGE_EMAIL % fill logger.info('sending email to %s' % settings.SERVER_EMAIL) send_mail(subject='BioStar: account merge request', message=body, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[ settings.DEFAULT_FROM_EMAIL ], fail_silently=False) messages.info(request, "Your request for account merge has been submitted for review.") return html.redirect( user.profile.get_absolute_url() ) except Exception, exc: messages.error(request, 'Submission error %s' % exc)
def user_profile(request, uid, tab='activity'): "User's profile page" if not models.User.objects.filter(id=uid): messages.error(request, "This user does not exist. It has perhaps been deleted.") return html.redirect("/") user = request.user target = models.User.objects.get(id=uid) awards = [] page = None # some information is only visible to the user target.writeable = auth.authorize_user_edit(target=target, user=user, strict=False) target.showall = (target == user) params = html.Params(tab=tab, sort='', title="User %s" % target.profile.display_name) # these do not actually get executed unless explicitly rendered in the page bookmarks = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).select_related('post', 'post__author__profile').order_by('id') awards = models.Award.objects.filter(user=target).select_related('badge').order_by('-date') # we need to collate and count the awards answer_count = models.Post.objects.filter(author=target, type=POST_ANSWER).count() question_count = models.Post.objects.filter(author=target, type=POST_QUESTION).count() comment_count = models.Post.objects.filter(author=target, type=POST_COMMENT).count() post_count = models.Post.objects.filter(author=target).count() vote_count = models.Vote.objects.filter(author=target).count() award_count = models.Award.objects.filter(user=target).count() note_count = models.Note.objects.filter(target=target, unread=True).count() bookmarks_count = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).count() if tab in [ 'activity', 'created' ]: if tab == 'created': notes = models.Note.objects.filter(sender=target, target=target, type=NOTE_USER).select_related('author', 'author__profile', 'root').order_by('-date') else: notes = models.Note.objects.filter(target=target, type=NOTE_USER).exclude(sender=target).select_related('author', 'author__profile', 'root').order_by('-date') page = get_page(request, notes, per_page=15) # we evalute it here so that subsequent status updates won't interfere page.object_list = list(page.object_list) if user == target: models.Note.objects.filter(target=target, unread=True).update(unread=False) models.UserProfile.objects.filter(user=target).update(new_messages=0) note_count = 0 elif tab == 'bookmarks': bookmarks = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).select_related('post', 'post__author__profile').order_by('-date') page = get_page(request, bookmarks, per_page=15) elif tab =="moderator": notes = models.Note.objects.filter(target=target, type=NOTE_MODERATOR).select_related('author', 'author__profile').order_by('-date') page = get_page(request, notes, per_page=15) params.update(dict(question_count=question_count, answer_count=answer_count, note_count=note_count, bookmarks_count=bookmarks_count, comment_count=comment_count, post_count=post_count, vote_count=vote_count, award_count=award_count)) return html.template(request, name='user.profile.html', awards=awards, user=request.user,target=target, params=params, page=page)
def user_edit(request, uid): "User's profile page" target = models.User.objects.select_related('profile').get(id=uid) allow = auth.authorize_user_edit(target=target, user=request.user, strict=False) if not allow: messages.error(request, "unable to edit this user") return html.redirect(target.profile.get_absolute_url() ) # valid incoming fields fields = "display_name about_me website location my_tags scholar hide_ads".split() if request.method == 'GET': initial = dict(email=target.email) for field in fields: initial[field] = getattr(target.profile, field) or '' form = UserForm(initial) return html.template(request, name='user.edit.html', target=target, form=form) elif request.method == 'POST': form = UserForm(request.POST) if not form.is_valid(): return html.template(request, name='user.edit.html', target=target, form=form) else: for field in fields: setattr(target.profile, field, form.cleaned_data[field]) # hiding ads requires a minimum reputation if target.profile.hide_ads and target.profile.score < settings.AD_MIN_REP: target.profile.hide_ads = False messages.warning(request, "The reputation needed to hide ads is %s" % (settings.AD_MIN_REP * 10)) # check the new email new_email = form.cleaned_data['email'].strip() if new_email != target.email and models.User.objects.filter(email=new_email): # cannot set your email to an existing other user 'semail messages.error(request, "This email is aready taken - please merge the accounts!") else: target.email = new_email target.profile.save() target.save() url = reverse('main.server.views.user_profile', kwargs=dict(uid=target.id)) return html.redirect(url)
def post_reparent(request, pid, rid=0): "Reparent a post" post = models.Post.objects.get(id=pid) root = post.root parent = post.parent allow = auth.authorize_post_edit(post=post, user=request.user, strict=False) if not allow: messages.error(request, "Reparent access denied") return html.redirect(post.get_absolute_url()) if post.type in POST_TOPLEVEL or post == post.root: messages.error(request, "Cannot reparent a toplevel post") return html.redirect(post.get_absolute_url()) # these are the valid targets targets = models.Post.objects.filter(root=root).select_related('author', 'author__profile').exclude(id__in=(post.id, parent.id)) target = request.REQUEST.get('target') if target: target = models.Post.objects.get(id=target) if target not in targets: messages.error(request, "Invalid reparent %s -> %s" % (post.id, target.id) ) return html.redirect(post.get_absolute_url()) # comment to comment reparent is not yet supported if target.type == POST_COMMENT and post.type == POST_COMMENT: messages.error(request, "Comment to comment reparent %s -> %s not implemented" % (post.id, target.id) ) return html.redirect(post.get_absolute_url()) # perfomr the reparent post.parent = target question = (target.type == POST_QUESTION) post.type = POST_ANSWER if question else POST_COMMENT post.save() # valid target to be applied messages.info(request, "Reparenting %s to %s" % (post.id, target.id)) return html.redirect(post.get_absolute_url()) return html.template(request, name='post.reparent.html', post=post, targets=targets)
def note_clear(request, uid): "Clears all notifications of a user" user = models.User.objects.get(pk=uid) # you may only delete your own messages if user == request.user: messages.info(request, "All messages have been deleted") models.Note.objects.filter(target=user).all().delete() else: messages.warning(request, "You may only delete your own messages") return html.redirect("/user/show/%s/" % user.id)
def show_post(post, anchor=None): """ Shows a post in full context """ # get the root of a post root = post.get_root() pid, slug = root.id, root.slug anchor = anchor or post.id url = '/post/show/%s/%s/#%s' % (pid, slug, anchor) return html.redirect(url)
def user_profile(request, uid, tab='activity'): "User's profile page" if not models.User.objects.filter(id=uid): messages.error(request, "This user does not exist. It has perhaps been deleted.") return html.redirect("/") user = request.user target = models.User.objects.get(id=uid) awards = [] page = None # some information is only visible to the user target.writeable = auth.authorize_user_edit(target=target, user=user, strict=False) target.showall = (target == user) params = html.Params(tab=tab, sort='') # these do not actually get executed unless explicitly rendered in the page bookmarks = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).select_related('post', 'post__author__profile').order_by('id') awards = models.Award.objects.filter(user=target).select_related('badge').order_by('-date') # we need to collate and count the awards answer_count = models.Post.objects.filter(author=target, type=POST_ANSWER).count() question_count = models.Post.objects.filter(author=target, type=POST_QUESTION).count() comment_count = models.Post.objects.filter(author=target, type=POST_COMMENT).count() post_count = models.Post.objects.filter(author=target).count() vote_count = models.Vote.objects.filter(author=target).count() award_count = models.Award.objects.filter(user=target).count() note_count = models.Note.objects.filter(target=target, unread=True).count() bookmarks_count = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).count() if tab == 'activity': notes = models.Note.objects.filter(target=target, type=NOTE_USER).select_related('author', 'author__profile', 'root').order_by('-date') page = get_page(request, notes, per_page=15) # we evalute it here so that subsequent status updates won't interfere page.object_list = list(page.object_list) if user==target: models.Note.objects.filter(target=target).update(unread=False) models.UserProfile.objects.filter(user=target).update(new_messages=0) note_count = 0 elif tab == 'bookmarks': bookmarks = models.Vote.objects.filter(author=target, type=VOTE_BOOKMARK).select_related('post', 'post__author__profile').order_by('-date') page = get_page(request, bookmarks, per_page=15) elif tab =="moderator": notes = models.Note.objects.filter(target=target, type=NOTE_MODERATOR).select_related('author', 'author__profile').order_by('-date') page = get_page(request, notes, per_page=15) params.update(dict(question_count=question_count, answer_count=answer_count, note_count=note_count, bookmarks_count=bookmarks_count, comment_count=comment_count, post_count=post_count, vote_count=vote_count, award_count=award_count)) return html.template(request, name='user.profile.html', awards=awards, user=request.user,target=target, params=params, page=page)
def get(self, *args, **kwargs): url = reverse(AdView.url) m = models.Ad pk = kwargs['pk'] user = self.request.user ad = models.Ad.objects.get(pk=pk) ad.start = allow_start(user)(ad=ad, user=user) ad.stop = allow_stop(ad=ad, user=user) now = datetime.now() ad.expiration_date = now + timedelta(days=30) action = self.request.GET.get("action", "") if action == "start": if allow_start(user)(ad, user): ad.status_by = user ad.status = m.RUNNING ad.save() messages.info(self.request, 'Ad started.') else: messages.error(self.request, 'Ad starting was denied.') return html.redirect(url) if action == "stop": if allow_stop(ad, user): ad.status_by = user ad.status = m.STOPPED ad.save() messages.info(self.request, 'Ad stopped.') else: messages.error(self.request, 'Ad stopping was denied') return html.redirect(url) messages.error(self.request, 'Action not recognized') return html.redirect(url)
def approve_merge(request, master_id, remove_id): "Approves an account merge request" user = request.user if not user.profile.is_admin: messages.error(request, 'Error: approving user not an administrator!') return html.redirect("/") try: master = models.User.objects.get(id=master_id) remove = models.User.objects.get(id=remove_id) with transaction.commit_on_success(): migrate(master, remove) remove.delete() fill = dict( domain=settings.SITE_DOMAIN, profile_url=master.profile.get_absolute_url() ) body = ACCOUNT_APPROVAL_EMAIL % fill send_mail(subject='BioStar: account merge complete', message=body, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[ settings.SERVER_EMAIL, master.email ], fail_silently=False) except Exception, exc: messages.error(request, 'Merge error: %s' % exc) return html.redirect("/")
def post_show(request, pid): "Returns a question with all answers" user = request.user query = get_post_manager(request) try: root = query.get(id=pid) # update the views for the question models.update_post_views(post=root, request=request, hours=settings.POST_VIEW_RANK_GAIN) except models.Post.DoesNotExist, exc: messages.warning(request, 'The post that you are looking for does not exists. Perhaps it was deleted!') return html.redirect("/")
def test_login(request, uid, token): "This will allow test logins. Don't turn it on during production!" from django.contrib.auth import authenticate, login allow = (token == settings.SELENIUM_TEST_LOGIN_TOKEN) if settings.DEBUG and settings.SELENIUM_TEST_LOGIN_TOKEN and allow: user = models.User.objects.get(id=uid) password = models.make_uuid() user.set_password(password) user.save() user = authenticate(username=user.username, password=password) login(request=request, user=user) messages.info(request, "Test login complete.") else: messages.error(request, "Test login failed.") return html.redirect("/")
def private_message(request, uid): "General moderation function" user = request.user target = models.User.objects.get(id=uid) # TODO allow users to opt out from getting messages # get the message from the body text = request.POST.get("message","").strip()[:1500] text = html.generate(text) text = html.sanitize(text) if not text: messages.error(request, 'Empty message') else: content = "PM to %s: %s" % (notegen.userlink(target), text) models.send_note(target=user, content=content, sender=user, both=False, unread=False, type=NOTE_PRIVATE, url=user.profile.get_absolute_url() ) content = "PM from %s: %s" % (notegen.userlink(user), text) models.send_note(target=target, content=content, sender=user, both=False, type=NOTE_PRIVATE, url=user.profile.get_absolute_url() ) messages.info(request, 'Your private message to <b>%s</b> has been sent!' % target.profile.display_name) return html.redirect( target.profile.get_absolute_url() )
def index(request, tab='all'): user = request.user auth = user.is_authenticated() # asking for an invalid tab if tab not in VALID_TABS: msg = html.sanitize('Unknown content type "%s"' % tab) messages.error(request, msg) return html.redirect("/") # populate the session data sess = middleware.Session(request) # get the sort order sort_type = sess.sort_order() # set the last active tab sess.set_tab(tab) # get the numerical value for these posts post_type = POST_TYPE_MAP.get(tab, tab) # override the sort order if the content so requires sort_type = 'creation' if tab=='recent' else sort_type # the params object will carry layout = settings.USER_PILL_BAR if auth else settings.ANON_PILL_BAR # wether to show the type of the post show_type = post_type in ('all', 'recent') if tab in VALID_PILLS: tab, pill = "posts", tab else: tab, pill = tab, "" params = html.Params(tab=tab, pill=pill, sort=sort_type, sort_choices=SORT_CHOICES, layout=layout, show_type=show_type, title="Bioinformatics Answers") # this will fill in the query (q) and the match (m)parameters params.parse(request) # returns the object manager that contains all or only visible posts posts = get_post_manager(request) # filter posts by type posts = filter_by_type(request=request, posts=posts, post_type=post_type) # sticky is not active on recent and all pages sticky = (tab != 'recent') and (pill != 'all') # order may change if it is invalid search posts = apply_sort(request=request, posts=posts, order=sort_type, sticky=sticky) # this is necessary because the planet posts require more attributes if tab == 'planet': models.decorate_posts(posts, request.user) # get the counts for the session counts = sess.get_counts(post_type) page = get_page(request, posts, per_page=POSTS_PER_PAGE) # save the session sess.save() # try to set a more informative title title_map = dict( questions="Bioinformatics Questions", unanswered="Unanswered Questions", tutorials="Bioinformatics Tutorials", jobs="Bioinformatics Jobs", videos="Bioinformatics Videos", news='Bioinformatics News', tools="Bioinformatics Tools", recent="Recent bioinformatics posts", planet="Bioinformatics Planet" ) params.title = title_map.get(tab, params.title) return html.template(request, name='index.html', page=page, params=params, counts=counts)
def post_show_redirect(request, pid): """ Permanent redirect from an old style post show """ url = reverse("post-show", kwargs=dict(pid=pid)) return html.redirect(url, permanent=True)
def redirect(post): return html.redirect( post.get_absolute_url() )
def bestof(request, tab='best'): messages.info(request, "Most <b>upvoted</b> active posts <b>this week!</b>") return html.redirect("/show/all/?sort=votes&since=this week")
def user_profile_redirect(request, uid, tab='activity'): """ User's profile page """ url = reverse("user-profile", kwargs=dict(uid=uid)) return html.redirect(url, permanent=True)
def blog_redirect(request, pid): "Used to be able to count the views for a blog" blog = models.Post.objects.get(id=pid, type=POST_BLOG) models.update_post_views(post=blog, request=request, hours=settings.BLOG_VIEW_RANK_GAIN) # 12 hour rank change return html.redirect( blog.get_absolute_url() )
def index(request, tab='all'): user = request.user auth = user.is_authenticated() # asking for an invalid tab if tab not in VALID_TABS: msg = html.sanitize('Unknown content type "%s"' % tab) messages.error(request, msg) return html.redirect("/") # populate the session data sess = middleware.Session(request) # get the sort order sort_type = sess.sort_order() # parse the date request since = request.GET.get('since', DATE_FILTER[0]).lower() # set the last active tab sess.set_tab(tab) # get the numerical value for these posts post_type = POST_TYPE_MAP.get(tab, tab) # override the sort order if the content so requires sort_type = 'creation' if tab=='recent' else sort_type # this here needs to be reworked TODO if tab == "best": sort_type = "votes" since = request.GET.get('since', 'this week') messages.info(request, "Most <b>upvoted</b> active posts of <b>%s!</b>" % since) elif tab == "bookmarked": sort_type = "bookmark" since = request.GET.get('since', 'this month') messages.info(request, "Most <b>bookmarked</b> active posts of <b>%s!</b>" % since) elif tab == "myvotes": sort_type = "votes__date" messages.info(request, "Posts created by you that have received up-votes from other users") elif tab == "mybookmarks": sort_type = "votes__date" messages.info(request, "Your bookmarked posts") elif tab == "myposts": sort_type = "creation" messages.info(request, "Posts created by you") # the params object will carry layout = settings.USER_PILL_BAR if auth else settings.ANON_PILL_BAR # wether to show the type of the post show_type = post_type in ('all', 'recent') show_search = True if tab in VALID_PILLS: tab, pill = "posts", tab else: tab, pill = tab, "" params = html.Params(tab=tab, pill=pill, sort=sort_type, sort_choices=SORT_CHOICES, date_filter=DATE_FILTER, since=since, layout=layout, show_type=show_type, title="Bioinformatics Answers", show_search=show_search) # this will fill in the query (q) and the match (m)parameters params.parse(request) # returns the object manager that contains all or only visible posts posts = get_post_manager(request) # filter posts by type posts = filter_by_type(request=request, posts=posts, post_type=post_type) # apply date filtering posts = filter_by_date(request=request, posts=posts, since=since) # reduce SQL query count by preselecting data that will be displayed posts = posts.select_related('author', 'author__profile', 'lastedit_user', 'lastedit_user__profile') # sticky is not active on recent and all pages sticky = (tab != 'recent') and (pill not in ('all', "best", "bookmarked")) # hackfix sticky = False if pill.startswith("my") else sticky # order may change if it is invalid search posts = apply_sort(request=request, posts=posts, order=sort_type, sticky=sticky) # get the counts for the session counts = sess.get_counts(post_type) page = get_page(request, posts, per_page=settings.POSTS_PER_PAGE) # save the session sess.save() # try to set a more informative title title_map = dict( questions="Bioinformatics Questions", unanswered="Unanswered Questions", tutorials="Bioinformatics Tutorials", jobs="Bioinformatics Jobs", videos="Bioinformatics Videos", news='Bioinformatics News', tools="Bioinformatics Tools", recent="Recent bioinformatics posts", planet="Bioinformatics Planet", galaxy="Galaxy on Biostar", bookmarked="Most bookmarked", ) params.title = title_map.get(pill) or title_map.get(tab, params.title) return html.template(request, name='index.html', page=page, params=params, counts=counts)
def post_redirect(request, pid): "Redirect to a post" post = models.Post.objects.get(id=pid) return html.redirect( post.get_absolute_url() )
master = models.User.objects.get(id=master_id) remove = models.User.objects.get(id=remove_id) with transaction.commit_on_success(): migrate(master, remove) remove.delete() fill = dict( domain=settings.SITE_DOMAIN, profile_url=master.profile.get_absolute_url() ) body = ACCOUNT_APPROVAL_EMAIL % fill send_mail('BioStar: account merge complete', body, settings.DEFAULT_FROM_EMAIL, [ master.email ], fail_silently=False) except Exception, exc: messages.error(request, 'Merge error: %s' % exc) return html.redirect("/") messages.info(request, 'Merge completed') return html.redirect("/") def test_login(request, uid, token): "This will allow test logins. Don't turn it on during production!" from django.contrib.auth import authenticate, login allow = (token == settings.SELENIUM_TEST_LOGIN_TOKEN) if settings.DEBUG and settings.SELENIUM_TEST_LOGIN_TOKEN and allow: user = models.User.objects.get(id=uid) password = models.make_uuid() user.set_password(password) user.save() user = authenticate(username=user.username, password=password) login(request=request, user=user) messages.info(request, "Test login complete.") else:
def index(request, tab='all'): user = request.user auth = user.is_authenticated() # asking for an invalid tab if tab not in VALID_TABS: msg = html.sanitize('Unknown content type "%s"' % tab) messages.error(request, msg) return html.redirect("/") # populate the session data sess = middleware.Session(request) # get the sort order sort_type = sess.sort_order() # parse the date request since = request.GET.get('since', DATE_FILTER[0]).lower() # set the last active tab sess.set_tab(tab) # get the numerical value for these posts post_type = POST_TYPE_MAP.get(tab, tab) # override the sort order if the content so requires sort_type = 'creation' if tab == 'recent' else sort_type # this here needs to be reworked TODO if tab == "best": sort_type = "votes" since = request.GET.get('since', 'this week') messages.info(request, "Most <b>upvoted</b> active posts of <b>%s!</b>" % since) elif tab == "bookmarked": sort_type = "bookmark" since = request.GET.get('since', 'this month') messages.info( request, "Most <b>bookmarked</b> active posts of <b>%s!</b>" % since) elif tab == "myvotes": sort_type = "votes__date" messages.info( request, "Posts created by you that have received up-votes from other users" ) elif tab == "mybookmarks": sort_type = "votes__date" messages.info(request, "Your bookmarked posts") elif tab == "myposts": sort_type = "creation" messages.info(request, "Posts created by you") # the params object will carry layout = settings.USER_PILL_BAR if auth else settings.ANON_PILL_BAR # wether to show the type of the post show_type = post_type in ('all', 'recent') show_search = True if tab in VALID_PILLS: tab, pill = "posts", tab else: tab, pill = tab, "" params = html.Params(tab=tab, pill=pill, sort=sort_type, sort_choices=SORT_CHOICES, date_filter=DATE_FILTER, since=since, layout=layout, show_type=show_type, title="Bioinformatics Answers", show_search=show_search) # this will fill in the query (q) and the match (m)parameters params.parse(request) # returns the object manager that contains all or only visible posts posts = get_post_manager(request) # filter posts by type posts = filter_by_type(request=request, posts=posts, post_type=post_type) # apply date filtering posts = filter_by_date(request=request, posts=posts, since=since) # reduce SQL query count by preselecting data that will be displayed posts = posts.select_related('author', 'author__profile', 'lastedit_user', 'lastedit_user__profile') # sticky is not active on recent and all pages sticky = (tab != 'recent') and (pill not in ('all', "best", "bookmarked")) # hackfix sticky = False if pill.startswith("my") else sticky # order may change if it is invalid search posts = apply_sort(request=request, posts=posts, order=sort_type, sticky=sticky) # get the counts for the session counts = sess.get_counts(post_type) page = get_page(request, posts, per_page=settings.POSTS_PER_PAGE) # save the session sess.save() # try to set a more informative title title_map = dict( questions="Bioinformatics Questions", unanswered="Unanswered Questions", tutorials="Bioinformatics Tutorials", jobs="Bioinformatics Jobs", videos="Bioinformatics Videos", news='Bioinformatics News', tools="Bioinformatics Tools", recent="Recent bioinformatics posts", planet="Bioinformatics Planet", galaxy="Galaxy on Biostar", bookmarked="Most bookmarked", ) params.title = title_map.get(pill) or title_map.get(tab, params.title) return html.template(request, name='index.html', page=page, params=params, counts=counts)
def bestof(request, tab='best'): messages.info(request, "Most <b>upvoted</b> active posts <b>this week!</b>") return html.redirect("/show/best/?sort=votes&since=this week")
def index(request, tab='all'): user = request.user auth = user.is_authenticated() # asking for an invalid tab if tab not in VALID_TABS: msg = html.sanitize('Unknown content type "%s"' % tab) messages.error(request, msg) return html.redirect("/") # populate the session data sess = middleware.Session(request) # get the sort order sort_type = sess.sort_order() # set the last active tab sess.set_tab(tab) # get the numerical value for these posts post_type = POST_TYPE_MAP.get(tab, tab) # override the sort order if the content so requires sort_type = 'creation' if tab == 'recent' else sort_type # the params object will carry layout = settings.USER_PILL_BAR if auth else settings.ANON_PILL_BAR # wether to show the type of the post show_type = post_type in ('all', 'recent') if tab in VALID_PILLS: tab, pill = "posts", tab else: tab, pill = tab, "" params = html.Params(tab=tab, pill=pill, sort=sort_type, sort_choices=SORT_CHOICES, layout=layout, show_type=show_type, title="Bioinformatics Answers") # this will fill in the query (q) and the match (m)parameters params.parse(request) # returns the object manager that contains all or only visible posts posts = get_post_manager(request) # filter posts by type posts = filter_by_type(request=request, posts=posts, post_type=post_type) # sticky is not active on recent and all pages sticky = (tab != 'recent') and (pill != 'all') # order may change if it is invalid search posts = apply_sort(request=request, posts=posts, order=sort_type, sticky=sticky) # this is necessary because the planet posts require more attributes if tab == 'planet': models.decorate_posts(posts, request.user) # get the counts for the session counts = sess.get_counts(post_type) page = get_page(request, posts, per_page=POSTS_PER_PAGE) # save the session sess.save() # try to set a more informative title title_map = dict(questions="Bioinformatics Questions", unanswered="Unanswered Questions", tutorials="Bioinformatics Tutorials", jobs="Bioinformatics Jobs", videos="Bioinformatics Videos", news='Bioinformatics News', tools="Bioinformatics Tools", recent="Recent bioinformatics posts", planet="Bioinformatics Planet") params.title = title_map.get(tab, params.title) return html.template(request, name='index.html', page=page, params=params, counts=counts)
def redirect_tag(request, tag): try: return html.redirect("/show/tag/%s/" % tag, permanent=True) except Exception, exc: messages.error(request, "Unable to redirect: %s" % exc) return html.redirect("/")
master = models.User.objects.get(id=master_id) remove = models.User.objects.get(id=remove_id) with transaction.commit_on_success(): migrate(master, remove) remove.delete() fill = dict( domain=settings.SITE_DOMAIN, profile_url=master.profile.get_absolute_url() ) body = ACCOUNT_APPROVAL_EMAIL % fill send_mail(subject='BioStar: account merge complete', message=body, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[ settings.SERVER_EMAIL, master.email ], fail_silently=False) except Exception, exc: messages.error(request, 'Merge error: %s' % exc) return html.redirect("/") messages.info(request, 'Merge completed') return html.redirect("/") def authorize_external_user(request, data): """ Authorizes and returns a user based on a trusted JSON string """ username = data['username'] # get the user users = models.User.objects.filter(username=username) if users: # this user already exists in the database user = users[0] if user.profile.type != USER_EXTERNAL: