def gravatar(user, size): """ Creates an ``<img>`` for a user's Gravatar with a given size. This tag can accept a User object, or a dict containing the appropriate values. """ #todo: rewrite using get_from_dict_or_object gravatar_hash = functions.get_from_dict_or_object(user, 'gravatar') default = askbot_settings.DEFAULT_GRAVATAR username = functions.get_from_dict_or_object(user, 'username') user_id = functions.get_from_dict_or_object(user, 'id') slug = slugify(username) user_profile_url = reverse( 'user_profile', kwargs={'id':user_id, 'slug':slug} ) #safe_username = template.defaultfilters.urlencode(username) return mark_safe(GRAVATAR_TEMPLATE % { 'user_profile_url': user_profile_url, 'size': size, 'gravatar_hash': gravatar_hash, 'default': default, 'alt_text': _('%(username)s gravatar image') % {'username': username}, 'username': username, })
def add_group(request): group_name = request.POST.get('group') if group_name: group = models.Group.objects.get_or_create(name=group_name, openness=models.Group.OPEN, user=request.user) url = reverse('users_by_group', kwargs={'group_id': group.id, 'group_slug': slugify(group_name)}) response_dict = dict(group_name=group_name, url=url) return response_dict
def get_absolute_url(self): return '%(base)s%(slug)s?answer=%(id)d#%(id)d' % \ { 'base': reverse('question', args=[self.question.id]), 'slug': django_urlquote(slugify(self.question.title)), 'id': self.id }
def _get_group_url(group): """calculates url to the group based on its id and name""" group_slug = slugify(group['name']) return reverse( 'users_by_group', kwargs={'group_id': group['id'], 'group_slug': group_slug} )
def __init__(self, time, type, title, summary, url): self.time = time self.type = get_type_name(type) self.type_id = type self.title = title self.summary = summary slug_title = slugify(title) self.title_link = url
def user_primary_group(user): group = user.get_primary_group() group_name = group.name.replace('-', ' ') group_url = reverse('users_by_group', args=(group.id, slugify(group_name))) return { 'group_name': group_name, 'group_url': group_url }
def test_user_urls_logged_in(self): # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way user = models.User.objects.get(id=2) name_slug = slugify(user.username) # works only with builtin django_authopenid self.client.login(method='force', user_id=2) self.try_url('user_subscriptions', kwargs={'id': 2, 'slug': name_slug}, template='user_profile/user_email_subscriptions.jinja') self.try_url('edit_user', kwargs={'id': 2}, template='user_profile/user_edit.jinja') self.client.logout()
def application_settings(request): """The context processor function""" if not request.path.startswith('/' + settings.ASKBOT_URL): #todo: this is a really ugly hack, will only work #when askbot is installed not at the home page. #this will not work for the #heavy modders of askbot, because their custom pages #will not receive the askbot settings in the context #to solve this properly we should probably explicitly #add settings to the context per page return {} my_settings = askbot_settings.as_dict() my_settings['LANGUAGE_CODE'] = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE) my_settings['ALLOWED_UPLOAD_FILE_TYPES'] = \ settings.ASKBOT_ALLOWED_UPLOAD_FILE_TYPES my_settings['ASKBOT_URL'] = settings.ASKBOT_URL my_settings['STATIC_URL'] = settings.STATIC_URL my_settings['ASKBOT_CSS_DEVEL'] = getattr( settings, 'ASKBOT_CSS_DEVEL', False ) my_settings['USE_LOCAL_FONTS'] = getattr( settings, 'ASKBOT_USE_LOCAL_FONTS', False ) my_settings['DEBUG'] = settings.DEBUG my_settings['USING_RUNSERVER'] = 'runserver' in sys.argv my_settings['ASKBOT_VERSION'] = askbot.get_version() my_settings['LOGIN_URL'] = url_utils.get_login_url() my_settings['LOGOUT_URL'] = url_utils.get_logout_url() my_settings['LOGOUT_REDIRECT_URL'] = url_utils.get_logout_redirect_url() my_settings['USE_ASKBOT_LOGIN_SYSTEM'] = 'askbot.deps.django_authopenid' \ in settings.INSTALLED_APPS context = { 'settings': my_settings, 'skin': get_skin(request), 'moderation_items': api.get_info_on_moderation_items(request.user), 'noscript_url': const.DEPENDENCY_URLS['noscript'], } if askbot_settings.GROUPS_ENABLED: groups = models.Group.objects.exclude( name__startswith='_internal_' ).values('id', 'name') group_list = [] for group in groups: group_slug = slugify(group['name']) link = reverse('users_by_group', kwargs={'group_id': group['id'], 'group_slug': group_slug}) group_list.append({'name': group['name'], 'link': link}) context['group_list'] = simplejson.dumps(group_list) return context
def test_user_network(self): user2 = self.create_user('user2') user2.follow_user(self.user) self.user.follow_user(user2) name_slug = slugify(self.user.username) kwargs={'id': self.user.id, 'slug': name_slug} url = reverse('user_profile', kwargs=kwargs) response = self.client.get(url, data={'sort':'network'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'user_profile/user_network.html')
def __init__(self, time, type, title, summary, answer_id, question_id): self.time = time self.type = get_type_name(type) self.type_id = type self.title = title self.summary = summary slug_title = slugify(title) self.title_link = reverse("question", kwargs={"id": question_id}) + u"%s" % slug_title if int(answer_id) > 0: self.title_link += "#%s" % answer_id
def test_user_network(self): user2 = self.create_user("user2") user2.follow_user(self.user) self.user.follow_user(user2) name_slug = slugify(self.user.username) kwargs = {"id": self.user.id, "slug": name_slug} url = reverse("user_profile", kwargs=kwargs) response = self.client.get(url, data={"sort": "network"}) self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "user_profile/user_network.html")
def proto_test_user_urls(self, status_code): user = models.User.objects.get(id=2) name_slug = slugify(user.username) self.try_url( "user_profile", kwargs={"id": 2, "slug": name_slug}, status_code=status_code, data={"sort": "stats"}, template="user_profile/user_stats.html", ) self.try_url( "user_profile", kwargs={"id": 2, "slug": name_slug}, status_code=status_code, data={"sort": "recent"}, template="user_profile/user_recent.html", ) self.try_url( "user_profile", kwargs={"id": 2, "slug": name_slug}, status_code=status_code, data={"sort": "inbox"}, template="authopenid/signin.html", follow=True, ) self.try_url( "user_profile", kwargs={"id": 2, "slug": name_slug}, status_code=status_code, data={"sort": "reputation"}, template="user_profile/user_reputation.html", ) self.try_url( "user_profile", kwargs={"id": 2, "slug": name_slug}, status_code=status_code, data={"sort": "votes"}, template="authopenid/signin.html", follow=True, ) self.try_url( "user_profile", kwargs={"id": 2, "slug": name_slug}, status_code=status_code, data={"sort": "favorites"}, template="user_profile/user_favorites.html", ) self.try_url( "user_profile", kwargs={"id": 2, "slug": name_slug}, status_code=status_code, data={"sort": "email_subscriptions"}, template="authopenid/signin.html", follow=True, )
def clean(self,username): """ validate username """ if self.skip_clean == True: logging.debug('username accepted with no validation') return username if self.user_instance is None: pass elif isinstance(self.user_instance, User): if username == self.user_instance.username: logging.debug('username valid') return username else: raise TypeError('user instance must be of type User') try: username = super(UserNameField, self).clean(username) except forms.ValidationError: raise forms.ValidationError(self.error_messages['required']) username_re_string = const.USERNAME_REGEX_STRING #attention: here we check @ symbol in two places: input and the regex if askbot_settings.ALLOW_EMAIL_ADDRESS_IN_USERNAME is False: if '@' in username: raise forms.ValidationError(self.error_messages['noemail']) username_re_string = username_re_string.replace('@', '') username_regex = re.compile(username_re_string, re.UNICODE) if self.required and not username_regex.search(username): raise forms.ValidationError(self.error_messages['invalid']) if username in self.RESERVED_NAMES: raise forms.ValidationError(self.error_messages['forbidden']) if slugify(username) == '': raise forms.ValidationError(self.error_messages['meaningless']) try: user = self.db_model.objects.get( **{'%s' % self.db_field : username} ) if user: if self.must_exist: logging.debug('user exists and name accepted b/c here we validate existing user') return username else: raise forms.ValidationError(self.error_messages['taken']) except self.db_model.DoesNotExist: if self.must_exist: logging.debug('user must exist, so raising the error') raise forms.ValidationError(self.error_messages['missing']) else: logging.debug('user name valid!') return username except self.db_model.MultipleObjectsReturned: logging.debug('error - user with this name already exists') raise forms.ValidationError(self.error_messages['multiple-taken'])
def proto_test_user_urls(self, status_code): user = models.User.objects.get(id=2) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way name_slug = slugify(user.username) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort':'stats'}, template='user_profile/user_stats.html' ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort':'recent'}, template='user_profile/user_recent.html' ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort':'inbox'}, template='authopenid/signin.html', follow=True ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort':'reputation'}, template='user_profile/user_reputation.html' ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort':'votes'}, template='authopenid/signin.html', follow = True ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort':'favorites'}, template='user_profile/user_favorites.html' ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort':'email_subscriptions'}, template='authopenid/signin.html', follow = True )
def test_user_urls_logged_in(self): user = models.User.objects.get(id=2) name_slug = slugify(user.username) #works only with builtin django_authopenid self.client.login(method = 'force', user_id = 2) self.try_url( 'user_subscriptions', kwargs = {'id': 2, 'slug': name_slug}, template = 'user_profile/user_email_subscriptions.html' ) self.client.logout()
def test_user_urls_logged_in(self): user = models.User.objects.get(id=2) name_slug = slugify(user.username) # works only with builtin django_authopenid self.client.login(method="force", user_id=2) self.try_url( "user_subscriptions", kwargs={"id": 2, "slug": name_slug}, template="user_profile/user_email_subscriptions.html", ) self.client.logout()
def test_inbox_page(self): # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way asker = models.User.objects.get(id=2) question = asker.post_question( title='How can this happen?', body_text='This is the body of my question', tags='question answer test', ) responder = models.User.objects.get(id=3) responder.post_answer(question=question, body_text='this is the answer text') self.client.login(method='force', user_id=asker.id) self.try_url('user_profile', kwargs={'id': asker.id, 'slug': slugify(asker.username)}, data={'sort': 'inbox'}, template='user_inbox/responses.jinja')
def __init__(self, time, type, title, summary, problem_id, exercise_id): self.time = time self.type = get_type_name(type) self.type_id = type self.title = title self.summary = summary slug_title = slugify(title) self.title_link = reverse( 'exercise', kwargs={'id':exercise_id} ) + u'%s' % slug_title if int(problem_id) > 0: self.title_link += '#%s' % problem_id
def __init__(self, time, type, title, summary, answer_id, question_id): self.time = time self.type = get_type_name(type) self.type_id = type self.title = title self.summary = summary slug_title = slugify(title) self.title_link = reverse( 'question', kwargs={'id':question_id} ) + u'%s' % slug_title if int(answer_id) > 0: self.title_link += '#%s' % answer_id
def user(request, id, slug=None, tab_name=None): """Main user view function that works as a switchboard id - id of the profile owner todo: decide what to do with slug - it is not used in the code in any way """ profile_owner = get_object_or_404(models.User, id = id) if profile_owner.is_blocked(): if request.user.is_anonymous() \ or not request.user.is_administrator_or_moderator(): raise Http404 if slugify(profile_owner.username) != slug: view_url = profile_owner.get_profile_url() + '?' \ + urllib.urlencode(request.REQUEST) return HttpResponseRedirect(view_url) if not tab_name: tab_name = request.GET.get('sort', 'stats') can_show_karma = models.user_can_see_karma(request.user, profile_owner) if can_show_karma == False and tab_name == 'reputation': raise Http404 user_view_func = USER_VIEW_CALL_TABLE.get(tab_name, user_stats) search_state = SearchState( scope=None, sort=None, query=None, tags=None, author=None, page=None, page_size=const.USER_POSTS_PAGE_SIZE, user_logged_in=profile_owner.is_authenticated(), ) context = { 'view_user': profile_owner, 'can_show_karma': can_show_karma, 'search_state': search_state, 'user_follow_feature_on': ('followit' in django_settings.INSTALLED_APPS), } if CUSTOM_TAB: context['custom_tab_name'] = CUSTOM_TAB['NAME'] context['custom_tab_slug'] = CUSTOM_TAB['SLUG'] return user_view_func(request, profile_owner, context)
def test_inbox_page(self): asker = models.User.objects.get(id=2) question = asker.post_question( title="How can this happen?", body_text="This is the body of my question", tags="question answer test" ) responder = models.User.objects.get(id=3) responder.post_answer(question=question, body_text="this is the answer text") self.client.login(method="force", user_id=asker.id) self.try_url( "user_profile", kwargs={"id": asker.id, "slug": slugify(asker.username)}, data={"sort": "inbox"}, template="user_profile/user_inbox.html", )
def get_tag_subscribers(request): tag_name = request.GET['tag_name'] subscribers = list(models.User.objects.filter( tag_selections__tag__name = tag_name, tag_selections__reason__contains = 'S' ).values('id', 'username')) subscribers.extend(list(models.User.objects.filter( email_tag_filter_strategy = const.INCLUDE_ALL ).values('id','username'))) for subscriber in subscribers: subscriber['slug'] = slug.slugify(subscriber['username']) return {'subscribers': subscribers}
def get_absolute_url(self, no_slug = False): if self.is_answer(): return u'%(base)s%(slug)s?answer=%(id)d#answer-container-%(id)d' % \ { 'base': urlresolvers.reverse('question', args=[self.question.id]), 'slug': django_urlquote(slugify(self.question.title)), 'id': self.id } elif self.is_question(): url = urlresolvers.reverse('question', args=[self.id]) if no_slug == True: return url else: return url + django_urlquote(self.slug) raise NotImplementedError
def user_select_languages(request, id=None, slug=None): if request.method != 'POST': raise django_exceptions.PermissionDenied user = get_object_or_404(models.User, id=id) if not(request.user.id == user.id or request.user.is_administrator()): raise django_exceptions.PermissionDenied form = forms.LanguagePrefsForm(request.POST) if form.is_valid(): user.set_languages(form.cleaned_data['languages']) user.set_primary_language(form.cleaned_data['primary_language']) user.save() return redirect('user_subscriptions', id=user.id, slug=slugify(user.username))
def user_select_languages(request, id=None, slug=None): if request.method != "POST": raise django_exceptions.PermissionDenied user = get_object_or_404(models.User, id=id) if not (request.user.id == user.id or request.user.is_administrator()): raise django_exceptions.PermissionDenied languages = request.POST.getlist("languages") user.languages = " ".join(languages) user.save() redirect_url = reverse("user_subscriptions", kwargs={"id": user.id, "slug": slugify(user.username)}) return HttpResponseRedirect(redirect_url)
def test_user_urls(self): user = models.User.objects.get(id=2) name_slug = slugify(user.username) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, data={'sort':'stats'}, template='user_profile/user_stats.html' ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, data={'sort':'recent'}, template='user_profile/user_recent.html' ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, data={'sort':'inbox'}, template='authopenid/signin.html', follow=True ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, data={'sort':'reputation'}, template='user_profile/user_reputation.html' ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, data={'sort':'votes'}, template='authopenid/signin.html', follow = True ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, data={'sort':'favorites'}, template='user_profile/user_favorites.html' ) self.try_url( 'user_profile', kwargs={'id': 2, 'slug': name_slug}, data={'sort':'email_subscriptions'}, template='authopenid/signin.html', follow = True )
def clean(self,username): """ validate username """ if self.skip_clean == True: logging.debug('username accepted with no validation') return username if self.user_instance is None: pass elif isinstance(self.user_instance, User): if username == self.user_instance.username: logging.debug('username valid') return username else: raise TypeError('user instance must be of type User') try: username = super(UserNameField, self).clean(username) except forms.ValidationError: raise forms.ValidationError(self.error_messages['required']) username_regex = re.compile(const.USERNAME_REGEX_STRING, re.UNICODE) if self.required and not username_regex.search(username): raise forms.ValidationError(self.error_messages['invalid']) if username in self.RESERVED_NAMES: raise forms.ValidationError(self.error_messages['forbidden']) if slugify(username, force_unidecode = True) == '': raise forms.ValidationError(self.error_messages['meaningless']) try: user = self.db_model.objects.get( **{'%s' % self.db_field : username} ) if user: if self.must_exist: logging.debug('user exists and name accepted b/c here we validate existing user') return username else: raise forms.ValidationError(self.error_messages['taken']) except self.db_model.DoesNotExist: if self.must_exist: logging.debug('user must exist, so raising the error') raise forms.ValidationError(self.error_messages['missing']) else: logging.debug('user name valid!') return username except self.db_model.MultipleObjectsReturned: logging.debug('error - user with this name already exists') raise forms.ValidationError(self.error_messages['multiple-taken'])
def test_user_urls_logged_in(self): user = models.User.objects.get( id=2 ) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way name_slug = slugify(user.username) # works only with builtin django_authopenid self.client.login( method="force", user_id=2 ) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way self.try_url( "user_subscriptions", kwargs={ "id": 2, "slug": name_slug, }, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way template="user_profile/user_email_subscriptions.html", ) self.client.logout()
def test_inbox_page(self): asker = models.User.objects.get( id=2 ) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way question = asker.post_question( title="How can this happen?", body_text="This is the body of my question", tags="question answer test" ) responder = models.User.objects.get( id=3 ) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way responder.post_answer(question=question, body_text="this is the answer text") self.client.login(method="force", user_id=asker.id) self.try_url( "user_profile", kwargs={"id": asker.id, "slug": slugify(asker.username)}, data={"sort": "inbox"}, template="user_inbox/responses.html", )
def test_inbox_page(self): asker = models.User.objects.get(id = 2) question = asker.post_question( title = 'How can this happen?', body_text = 'This is the body of my question', tags = 'question answer test', ) responder = models.User.objects.get(id = 3) responder.post_answer( question = question, body_text = 'this is the answer text' ) self.client.login(method = 'force', user_id = asker.id) self.try_url( 'user_profile', kwargs={'id': asker.id, 'slug': slugify(asker.username)}, data={'sort':'inbox'}, template='user_profile/user_inbox.html', )
def test_inbox_page(self): asker = models.User.objects.get( id=2 ) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way question = asker.post_question( title='How can this happen?', body_text='This is the body of my question', tags='question answer test', ) responder = models.User.objects.get( id=3 ) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way responder.post_answer(question=question, body_text='this is the answer text') self.client.login(method='force', user_id=asker.id) self.try_url( 'user_profile', kwargs={ 'id': asker.id, 'slug': slugify(asker.username) }, data={'sort': 'inbox'}, template='user_inbox/responses.html', )
def show_users(request, by_group=False, group_id=None, group_slug=None): """Users view, including listing of users by group""" users = models.User.objects.exclude(status='b') group = None group_email_moderation_enabled = False user_can_join_group = False user_is_group_member = False if by_group == True: if askbot_settings.GROUPS_ENABLED == False: raise Http404 if group_id: if all((group_id, group_slug)) == False: return HttpResponseRedirect('groups') else: try: group = models.Tag.group_tags.get(id=group_id) group_email_moderation_enabled = \ ( askbot_settings.GROUP_EMAIL_ADDRESSES_ENABLED \ and askbot_settings.ENABLE_CONTENT_MODERATION ) user_can_join_group = group.group_profile.can_accept_user( request.user) except models.Tag.DoesNotExist: raise Http404 if group_slug == slugify(group.name): users = users.filter(group_memberships__group__id=group_id) if request.user.is_authenticated(): user_is_group_member = bool( users.filter(id=request.user.id).count()) else: group_page_url = reverse('users_by_group', kwargs={ 'group_id': group.id, 'group_slug': slugify(group.name) }) return HttpResponseRedirect(group_page_url) is_paginated = True sortby = request.GET.get('sort', 'reputation') if askbot_settings.KARMA_MODE == 'private' and sortby == 'reputation': sortby = 'newest' try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 search_query = request.REQUEST.get('query', "") if search_query == "": if sortby == "newest": order_by_parameter = '-date_joined' elif sortby == "last": order_by_parameter = 'date_joined' elif sortby == "user": order_by_parameter = 'username' else: # default order_by_parameter = '-reputation' objects_list = Paginator(users.order_by(order_by_parameter), const.USERS_PAGE_SIZE) base_url = request.path + '?sort=%s&' % sortby else: sortby = "reputation" matching_users = models.get_users_by_text_query(search_query) objects_list = Paginator(matching_users.order_by('-reputation'), const.USERS_PAGE_SIZE) base_url = request.path + '?name=%s&sort=%s&' % (search_query, sortby) try: users_page = objects_list.page(page) except (EmptyPage, InvalidPage): users_page = objects_list.page(objects_list.num_pages) paginator_data = { 'is_paginated': is_paginated, 'pages': objects_list.num_pages, 'page': page, 'has_previous': users_page.has_previous(), 'has_next': users_page.has_next(), 'previous': users_page.previous_page_number(), 'next': users_page.next_page_number(), 'base_url': base_url } paginator_context = functions.setup_paginator(paginator_data) # data = { 'active_tab': 'users', 'page_class': 'users-page', 'users': users_page, 'group': group, 'search_query': search_query, 'tab_id': sortby, 'paginator_context': paginator_context, 'group_email_moderation_enabled': group_email_moderation_enabled, 'user_can_join_group': user_can_join_group, 'user_is_group_member': user_is_group_member } return render_into_skin('users.html', data, request)
def show_users(request, by_group=False, group_id=None, group_slug=None): """Users view, including listing of users by group""" if askbot_settings.GROUPS_ENABLED and not by_group: default_group = models.Group.objects.get_global_group() group_slug = slugify(default_group.name) new_url = reverse('users_by_group', kwargs={ 'group_id': default_group.id, 'group_slug': group_slug }) return HttpResponseRedirect(new_url) users = models.User.objects.exclude(status='b') group = None group_email_moderation_enabled = False user_acceptance_level = 'closed' user_membership_level = 'none' if by_group == True: if askbot_settings.GROUPS_ENABLED == False: raise Http404 if group_id: if all((group_id, group_slug)) == False: return HttpResponseRedirect('groups') else: try: group = models.Group.objects.get(id=group_id) group_email_moderation_enabled = \ ( askbot_settings.GROUP_EMAIL_ADDRESSES_ENABLED \ and askbot_settings.ENABLE_CONTENT_MODERATION ) user_acceptance_level = group.get_openness_level_for_user( request.user) except models.Group.DoesNotExist: raise Http404 if group_slug == slugify(group.name): #filter users by full group memberships #todo: refactor as Group.get_full_members() full_level = models.GroupMembership.FULL memberships = models.GroupMembership.objects.filter( group=group, level=full_level) user_ids = memberships.values_list('user__id', flat=True) users = users.filter(id__in=user_ids) if request.user.is_authenticated(): membership = request.user.get_group_membership(group) if membership: user_membership_level = membership.get_level_display( ) else: group_page_url = reverse('users_by_group', kwargs={ 'group_id': group.id, 'group_slug': slugify(group.name) }) return HttpResponseRedirect(group_page_url) is_paginated = True sortby = request.GET.get('sort', 'reputation') if askbot_settings.KARMA_MODE == 'private' and sortby == 'reputation': sortby = 'newest' try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 search_query = request.GET.get('query', "") if search_query == "": if sortby == "newest": order_by_parameter = '-date_joined' elif sortby == "last": order_by_parameter = 'date_joined' elif sortby == "user": order_by_parameter = 'username' else: # default order_by_parameter = '-reputation' objects_list = Paginator(users.order_by(order_by_parameter), const.USERS_PAGE_SIZE) base_url = request.path + '?sort=%s&' % sortby else: sortby = "reputation" matching_users = models.get_users_by_text_query(search_query, users) objects_list = Paginator(matching_users.order_by('-reputation'), const.USERS_PAGE_SIZE) base_url = request.path + '?name=%s&sort=%s&' % (search_query, sortby) try: users_page = objects_list.page(page) except (EmptyPage, InvalidPage): users_page = objects_list.page(objects_list.num_pages) paginator_data = { 'is_paginated': is_paginated, 'pages': objects_list.num_pages, 'page': page, 'has_previous': users_page.has_previous(), 'has_next': users_page.has_next(), 'previous': users_page.previous_page_number(), 'next': users_page.next_page_number(), 'base_url': base_url } paginator_context = functions.setup_paginator(paginator_data) # #todo: move to contexts #extra context for the groups if askbot_settings.GROUPS_ENABLED: #todo: cleanup this branched code after groups are migrated to auth_group user_groups = models.Group.objects.exclude_personal() if len(user_groups) <= 1: assert (user_groups[0].name == askbot_settings.GLOBAL_GROUP_NAME) user_groups = None group_openness_choices = models.Group().get_openness_choices() else: user_groups = None group_openness_choices = None data = { 'active_tab': 'users', 'page_class': 'users-page', 'users': users_page, 'group': group, 'search_query': search_query, 'tab_id': sortby, 'paginator_context': paginator_context, 'group_email_moderation_enabled': group_email_moderation_enabled, 'user_acceptance_level': user_acceptance_level, 'user_membership_level': user_membership_level, 'user_groups': user_groups, 'group_openness_choices': group_openness_choices } return render(request, 'users.html', data)
def get_badge_name(cls, name): return slugify(cls.badge_exceptions.get(name, name).lower())
def _get_group_url(group): """calculates url to the group based on its id and name""" group_slug = slugify(group['name']) return reverse( 'users_by_group', kwargs={'group_id': group['id'], 'group_slug': group_slug})
def send_email_alerts(self): #does not change the database, only sends the email #todo: move this to template for user in User.objects.all(): user.add_missing_askbot_subscriptions() #todo: q_list is a dictionary, not a list q_list = self.get_updated_questions_for_user(user) if len(q_list.keys()) == 0: continue num_q = 0 for question, meta_data in q_list.items(): if meta_data['skip']: del q_list[question] else: num_q += 1 if num_q > 0: url_prefix = askbot_settings.APP_URL tag_summary = get_tag_summary_from_questions(q_list.keys()) question_count = len(q_list.keys()) subject_line = ungettext( '%(question_count)d updated question about %(topics)s', '%(question_count)d updated questions about %(topics)s', question_count) % { 'question_count': question_count, 'topics': tag_summary } #todo: send this to special log #print 'have %d updated questions for %s' % (num_q, user.username) text = ungettext('%(name)s, this is an update message header for %(num)d question', '%(name)s, this is an update message header for %(num)d questions',num_q) \ % {'num':num_q, 'name':user.username} text += '<ul>' items_added = 0 items_unreported = 0 for q, meta_data in q_list.items(): act_list = [] if meta_data['skip']: continue if items_added >= askbot_settings.MAX_ALERTS_PER_EMAIL: items_unreported = num_q - items_added #may be inaccurate actually, but it's ok else: items_added += 1 if meta_data['new_q']: act_list.append(_('new question')) format_action_count('%(num)d rev', meta_data['q_rev'], act_list) format_action_count('%(num)d ans', meta_data['new_ans'], act_list) format_action_count('%(num)d ans rev', meta_data['ans_rev'], act_list) act_token = ', '.join(act_list) text += '<li><a href="%s?sort=latest">%s</a> <font color="#777777">(%s)</font></li>' \ % (url_prefix + q.get_absolute_url(), q.title, act_token) text += '</ul>' text += '<p></p>' #if len(q_list.keys()) >= askbot_settings.MAX_ALERTS_PER_EMAIL: # text += _('There may be more questions updated since ' # 'you have logged in last time as this list is ' # 'abridged for your convinience. Please visit ' # 'the askbot and see what\'s new!<br>' # ) text += _( 'Please visit the askbot and see what\'s new! ' 'Could you spread the word about it - ' 'can somebody you know help answering those questions or ' 'benefit from posting one?') feeds = EmailFeedSetting.objects.filter(subscriber=user) feed_freq = [feed.frequency for feed in feeds] text += '<p></p>' if 'd' in feed_freq: text += _( 'Your most frequent subscription setting is \'daily\' ' 'on selected questions. If you are receiving more than one ' 'email per day' 'please tell about this issue to the askbot administrator.' ) elif 'w' in feed_freq: text += _( 'Your most frequent subscription setting is \'weekly\' ' 'if you are receiving this email more than once a week ' 'please report this issue to the askbot administrator.' ) text += ' ' text += _( 'There is a chance that you may be receiving links seen ' 'before - due to a technicality that will eventually go away. ' ) link = url_prefix + reverse('user_subscriptions', kwargs={ 'id': user.id, 'slug': slugify(user.username) }) text += _('go to %(email_settings_link)s to change ' 'frequency of email updates or ' '%(admin_email)s administrator') % { 'email_settings_link': link, 'admin_email': django_settings.ADMINS[0][1] } if DEBUG_THIS_COMMAND == True: recipient_email = django_settings.ADMINS[0][1] else: recipient_email = user.email mail.send_mail(subject_line=subject_line, body_text=text, recipient_list=[recipient_email])
def proto_test_user_urls(self, status_code): user = models.User.objects.get( id=2 ) # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way name_slug = slugify(user.username) self.try_url( 'user_profile', kwargs={ 'id': 2, 'slug': name_slug }, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort': 'stats'}, template='user_profile/user_stats.html') self.try_url( 'user_profile', kwargs={ 'id': 2, 'slug': name_slug }, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort': 'recent'}, template='user_profile/user_recent.html') self.try_url( 'user_profile', kwargs={ 'id': 2, 'slug': name_slug }, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort': 'inbox'}, template='authopenid/signin.html', follow=True) self.try_url( 'user_profile', kwargs={ 'id': 2, 'slug': name_slug }, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort': 'reputation'}, template='user_profile/user_reputation.html') self.try_url( 'user_profile', kwargs={ 'id': 2, 'slug': name_slug }, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort': 'votes'}, template='authopenid/signin.html', follow=True) self.try_url( 'user_profile', kwargs={ 'id': 2, 'slug': name_slug }, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort': 'favorites'}, template='user_profile/user_favorites.html') self.try_url( 'user_profile', kwargs={ 'id': 2, 'slug': name_slug }, # INFO: Hardcoded ID, might fail if DB allocates IDs in some non-continuous way status_code=status_code, data={'sort': 'email_subscriptions'}, template='authopenid/signin.html', follow=True)
def get_absolute_url(self, no_slug = False): url = reverse('question', args=[self.id]) if no_slug == True: return url else: return url + django_urlquote(slugify(self.title))
def _get_slug(self): return slugify(self.title)
def show_users(request, by_group=False, group_id=None, group_slug=None): """Users view, including listing of users by group""" if askbot_settings.GROUPS_ENABLED and not by_group: default_group = models.Group.objects.get_global_group() group_slug = slugify(default_group.name) new_url = reverse('users_by_group', kwargs={ 'group_id': default_group.id, 'group_slug': group_slug }) return HttpResponseRedirect(new_url) users = models.User.objects.exclude(askbot_profile__status='b').exclude( is_active=False).select_related('askbot_profile') if askbot.is_multilingual(): users = users.filter( localized_askbot_profiles__language_code=get_language(), localized_askbot_profiles__is_claimed=True) group = None group_email_moderation_enabled = False user_acceptance_level = 'closed' user_membership_level = 'none' if by_group == True: if askbot_settings.GROUPS_ENABLED == False: raise Http404 if group_id: if all((group_id, group_slug)) == False: return HttpResponseRedirect('groups') else: try: group = models.Group.objects.get(id=group_id) group_email_moderation_enabled = ( askbot_settings.GROUP_EMAIL_ADDRESSES_ENABLED \ and askbot_settings.CONTENT_MODERATION_MODE == 'premoderation' ) user_acceptance_level = group.get_openness_level_for_user( request.user) except models.Group.DoesNotExist: raise Http404 if group_slug == slugify(group.name): #filter users by full group memberships #todo: refactor as Group.get_full_members() full_level = models.GroupMembership.FULL memberships = models.GroupMembership.objects.filter( group=group, level=full_level) user_ids = memberships.values_list('user__id', flat=True) users = users.filter(id__in=user_ids) if request.user.is_authenticated(): membership = request.user.get_group_membership(group) if membership: user_membership_level = membership.get_level_display( ) else: group_page_url = reverse('users_by_group', kwargs={ 'group_id': group.id, 'group_slug': slugify(group.name) }) return HttpResponseRedirect(group_page_url) is_paginated = True form = forms.ShowUsersForm(request.REQUEST) form.full_clean() #always valid sort_method = form.cleaned_data['sort'] page = form.cleaned_data['page'] search_query = form.cleaned_data['query'] if search_query == '': if sort_method == 'newest': order_by_parameter = '-date_joined' elif sort_method == 'last': order_by_parameter = 'date_joined' elif sort_method == 'name': order_by_parameter = 'username' else: # default if askbot.is_multilingual(): order_by_parameter = '-localized_askbot_profiles__reputation' else: order_by_parameter = '-askbot_profile__reputation' objects_list = Paginator(users.order_by(order_by_parameter), askbot_settings.USERS_PAGE_SIZE) base_url = request.path + '?sort=%s&' % sort_method else: sort_method = 'reputation' matching_users = models.get_users_by_text_query(search_query, users) objects_list = Paginator( matching_users.order_by('-askbot_profile__reputation'), askbot_settings.USERS_PAGE_SIZE) base_url = request.path + '?name=%s&sort=%s&' % (search_query, sort_method) try: users_page = objects_list.page(page) except (EmptyPage, InvalidPage): users_page = objects_list.page(objects_list.num_pages) paginator_data = { 'is_paginated': is_paginated, 'pages': objects_list.num_pages, 'current_page_number': page, 'page_object': users_page, 'base_url': base_url } paginator_context = functions.setup_paginator(paginator_data) # #todo: move to contexts #extra context for the groups if askbot_settings.GROUPS_ENABLED: #todo: cleanup this branched code after groups are migrated to auth_group user_groups = models.Group.objects.exclude_personal() if len(user_groups) <= 1: assert (user_groups[0].name == askbot_settings.GLOBAL_GROUP_NAME) user_groups = None group_openness_choices = models.Group().get_openness_choices() else: user_groups = None group_openness_choices = None data = { 'active_tab': 'users', 'group': group, 'group_email_moderation_enabled': group_email_moderation_enabled, 'group_openness_choices': group_openness_choices, 'page_class': 'users-page', 'paginator_context': paginator_context, 'search_query': search_query, 'tab_id': sort_method, 'user_acceptance_level': user_acceptance_level, 'user_count': objects_list.count, 'user_groups': user_groups, 'user_membership_level': user_membership_level, 'users': users_page, } return render(request, 'users.html', data)
def user(request, id, slug=None, tab_name=None): """Main user view function that works as a switchboard id - id of the profile owner todo: decide what to do with slug - it is not used in the code in any way """ profile_owner = get_object_or_404(models.User, id=id) if profile_owner.is_blocked(): if request.user.is_anonymous() \ or not request.user.is_administrator_or_moderator(): raise Http404 if slugify(profile_owner.username) != slug: view_url = profile_owner.get_profile_url() + '?' \ + urllib.urlencode(request.REQUEST) return HttpResponseRedirect(view_url) if not tab_name: tab_name = request.GET.get('sort', 'stats') if askbot_settings.KARMA_MODE == 'public': can_show_karma = True elif askbot_settings.KARMA_MODE == 'hidden': can_show_karma = False else: if request.user.is_anonymous(): can_show_karma = False elif request.user.is_administrator_or_moderator(): can_show_karma = True elif request.user.pk == profile_owner.pk: can_show_karma = True else: can_show_karma = False if can_show_karma == False and tab_name == 'reputation': raise Http404 user_view_func = USER_VIEW_CALL_TABLE.get(tab_name, user_stats) search_state = SearchState( scope=None, sort=None, query=None, tags=None, author=None, page=None, page_size=const.USER_POSTS_PAGE_SIZE, user_logged_in=profile_owner.is_authenticated(), ) context = { 'view_user': profile_owner, 'can_show_karma': can_show_karma, 'search_state': search_state, 'user_follow_feature_on': ('followit' in django_settings.INSTALLED_APPS), } if CUSTOM_TAB: context['custom_tab_name'] = CUSTOM_TAB['NAME'] context['custom_tab_slug'] = CUSTOM_TAB['SLUG'] return user_view_func(request, profile_owner, context)
def send_email_alerts(self): #does not change the database, only sends the email #todo: move this to template for user in User.objects.all(): user.add_missing_askbot_subscriptions() #todo: q_list is a dictionary, not a list q_list = self.get_updated_questions_for_user(user) if len(q_list.keys()) == 0: continue num_q = 0 for question, meta_data in q_list.items(): if meta_data['skip']: del q_list[question] else: num_q += 1 if num_q > 0: threads = Thread.objects.filter(id__in=[qq.thread_id for qq in q_list.keys()]) tag_summary = Thread.objects.get_tag_summary_from_threads(threads) question_count = len(q_list.keys()) subject_line = ungettext( '%(question_count)d updated question about %(topics)s', '%(question_count)d updated questions about %(topics)s', question_count ) % { 'question_count': question_count, 'topics': tag_summary } #todo: send this to special log #print 'have %d updated questions for %s' % (num_q, user.username) text = ungettext( '<p>Dear %(name)s,</p><p>The following question has been updated ' '%(sitename)s</p>', '<p>Dear %(name)s,</p><p>The following %(num)d questions have been ' 'updated on %(sitename)s:</p>', num_q ) % { 'num':num_q, 'name':user.username, 'sitename': askbot_settings.APP_SHORT_NAME } text += '<ul>' items_added = 0 items_unreported = 0 for q, meta_data in q_list.items(): act_list = [] if meta_data['skip']: continue if items_added >= askbot_settings.MAX_ALERTS_PER_EMAIL: items_unreported = num_q - items_added #may be inaccurate actually, but it's ok else: items_added += 1 if meta_data['new_q']: act_list.append(_('new question')) format_action_count('%(num)d rev', meta_data['q_rev'],act_list) format_action_count('%(num)d ans', meta_data['new_ans'],act_list) format_action_count('%(num)d ans rev',meta_data['ans_rev'],act_list) act_token = ', '.join(act_list) text += '<li><a href="%s?sort=latest">%s</a> <font color="#777777">(%s)</font></li>' \ % (site_url(q.get_absolute_url()), q.thread.title, act_token) text += '</ul>' text += '<p></p>' #if len(q_list.keys()) >= askbot_settings.MAX_ALERTS_PER_EMAIL: # text += _('There may be more questions updated since ' # 'you have logged in last time as this list is ' # 'abridged for your convinience. Please visit ' # 'the askbot and see what\'s new!<br>' # ) link = reverse( 'user_subscriptions', kwargs = { 'id': user.id, 'slug': slugify(user.username) } ) text += _( '<p>Please remember that you can always <a ' 'href="%(email_settings_link)s">adjust</a> frequency of the email updates or ' 'turn them off entirely.<br/>If you believe that this message was sent in an ' 'error, please email about it the forum administrator at %(admin_email)s.</' 'p><p>Sincerely,</p><p>Your friendly %(sitename)s server.</p>' ) % { 'email_settings_link': site_url(link), 'admin_email': django_settings.ADMINS[0][1], 'sitename': askbot_settings.APP_SHORT_NAME } if DEBUG_THIS_COMMAND == True: recipient_email = django_settings.ADMINS[0][1] else: recipient_email = user.email mail.send_mail( subject_line = subject_line, body_text = text, recipient_list = [recipient_email] )