Esempio n. 1
0
def signature(request):
    # Intercept all requests if we can't use signature
    if not request.acl.usercp.can_use_signature():
        return error403(request)
    if request.user.signature_ban:
        return render_to_response('usercp/signature_banned.html',
                                  context_instance=RequestContext(request, {
                                      'tab': 'signature'}));

    siggy_text = ''
    message = request.messages.get_message('usercp_signature')
    if request.method == 'POST':
        form = SignatureForm(request.POST, request=request, initial={'signature': request.user.signature})
        if form.is_valid():
            request.user.signature = form.cleaned_data['signature']
            if request.user.signature:
                request.user.signature_preparsed = signature_markdown(request.acl,
                                                                      request.user.signature)
            else:
                request.user.signature_preparsed = None
            request.user.save(force_update=True)
            messages.success(request, _("Your signature has been changed."), 'usercp_signature')
            return redirect(reverse('usercp_signature'))
        else:
            message = Message(form.non_field_errors()[0], messages.ERROR)
    else:
        form = SignatureForm(request=request, initial={'signature': request.user.signature})

    return render_to_response('usercp/signature.html',
                              context_instance=RequestContext(request, {
                                  'message': message,
                                  'tab': 'signature',
                                  'form': form}));
Esempio n. 2
0
def form(request):
    """
    Allow admins to generate fancy statistic graphs for different models
    """
    models_map = {}
    for model in models.get_models():
        try:
            getattr(model.objects, "filter_stats")
            statistics_providers.append((str(model.__name__).lower(), model.statistics_name))
            models_map[str(model.__name__).lower()] = model
        except AttributeError:
            pass

    if not statistics_providers:
        """
        Something went FUBAR - Misago ships with some stats providers out of box
        If those providers cant be found, this means Misago filesystem is corrupted
        """
        return render_to_response("stats/not_available.html", context_instance=RequestContext(request))

    message = None
    if request.method == "POST":
        form = GenerateStatisticsForm(request.POST, provider_choices=statistics_providers, request=request)
        if form.is_valid():
            date_start = form.cleaned_data["date_start"]
            date_end = form.cleaned_data["date_end"]
            if date_start > date_end:
                # Reverse dates if start is after end
                date_temp = date_end
                date_end = date_start
                date_start = date_temp
            # Assert that dates are correct
            if date_end == date_start:
                message = Message(_("Start and end date are same"), messages.ERROR)
            elif check_dates(date_start, date_end, form.cleaned_data["stats_precision"]):
                message = check_dates(date_start, date_end, form.cleaned_data["stats_precision"])
            else:
                messages.success(request, _("Statistical report has been created."), "admin_stats")
                return redirect(
                    reverse(
                        "admin_stats_graph",
                        kwargs={
                            "model": form.cleaned_data["provider_model"],
                            "date_start": date_start.strftime("%Y-%m-%d"),
                            "date_end": date_end.strftime("%Y-%m-%d"),
                            "precision": form.cleaned_data["stats_precision"],
                        },
                    )
                )
        else:
            message = Message(form.non_field_errors()[0], messages.ERROR)
    else:
        form = GenerateStatisticsForm(provider_choices=statistics_providers, request=request)

    return render_to_response(
        "stats/form.html", {"form": form, "message": message}, context_instance=RequestContext(request)
    )
Esempio n. 3
0
def form(request):
    """
    Allow admins to generate fancy statistic graphs for different models
    """
    statistics_providers = []
    models_map = {}
    for model in models.get_models():
        try:
            getattr(model.objects, 'filter_stats')
            statistics_providers.append((str(model.__name__).lower(), model.statistics_name))
            models_map[str(model.__name__).lower()] = model
        except AttributeError:
            pass

    if not statistics_providers:
        """
        Something went FUBAR - Misago ships with some stats providers out of box
        If those providers cant be found, this means Misago filesystem is corrupted
        """
        return render_to_response('stats/not_available.html',
                                  context_instance=RequestContext(request));

    message = None
    if request.method == 'POST':
        form = GenerateStatisticsForm(request.POST, provider_choices=statistics_providers, request=request)
        if form.is_valid():
            date_start = form.cleaned_data['date_start']
            date_end = form.cleaned_data['date_end']
            if date_start > date_end:
                # Reverse dates if start is after end
                date_temp = date_end
                date_end = date_start
                date_start = date_temp
            # Assert that dates are correct
            if date_end == date_start:
                message = Message(_('Start and end date are same'), messages.ERROR)
            elif check_dates(date_start, date_end, form.cleaned_data['stats_precision']):
                message = check_dates(date_start, date_end, form.cleaned_data['stats_precision'])
            else:
                messages.success(request, _('Statistical report has been created.'), 'admin_stats')
                return redirect(reverse('admin_stats_graph', kwargs={
                                                       'model': form.cleaned_data['provider_model'],
                                                       'date_start': date_start.strftime('%Y-%m-%d'),
                                                       'date_end': date_end.strftime('%Y-%m-%d'),
                                                       'precision': form.cleaned_data['stats_precision']
                                                        }))
        else:
            message = Message(form.non_field_errors()[0], messages.ERROR)
    else:
        form = GenerateStatisticsForm(provider_choices=statistics_providers, request=request)

    return render_to_response('stats/form.html',
                              {
                              'form': form,
                              'message': message,
                              },
                              context_instance=RequestContext(request));
Esempio n. 4
0
def graph(request, model, date_start, date_end, precision):
    """
    Generate fancy graph for model and stuff
    """
    if date_start == date_end:
        # Bad dates
        raise error404(RequestContext)

    # Turn stuff into datetime's
    date_start = datetime.strptime(date_start, '%Y-%m-%d')
    date_end = datetime.strptime(date_end, '%Y-%m-%d')

    statistics_providers = []
    models_map = {}
    for model_obj in models.get_models():
        try:
            getattr(model_obj.objects, 'filter_stats')
            statistics_providers.append(
                (str(model_obj.__name__).lower(), model_obj.statistics_name))
            models_map[str(model_obj.__name__).lower()] = model_obj
        except AttributeError:
            pass

    if not statistics_providers:
        # Like before, q.q on lack of models
        return render_to_response('stats/not_available.html',
                                  context_instance=RequestContext(request))

    if not model in models_map or check_dates(date_start, date_end, precision):
        # Bad model name or graph data!
        raise error404(request)

    form = GenerateStatisticsForm(provider_choices=statistics_providers,
                                  request=request,
                                  initial={
                                      'provider_model': model,
                                      'date_start': date_start,
                                      'date_end': date_end,
                                      'stats_precision': precision
                                  })
    return render_to_response('stats/graph.html', {
        'title':
        models_map[model].statistics_name,
        'graph':
        build_graph(models_map[model], date_start, date_end, precision),
        'form':
        form,
        'message':
        request.messages.get_message('admin_stats'),
    },
                              context_instance=RequestContext(request))
Esempio n. 5
0
def new_threads(request, page=0):
    queryset = Thread.objects.filter(
        forum_id__in=Forum.objects.readable_forums(request.acl)).filter(
            deleted=False).filter(moderated=False)
    items_total = queryset.count()
    if items_total > (settings.threads_per_page * 3):
        items_total = settings.threads_per_page * 3
    try:
        pagination = make_pagination(page, items_total,
                                     settings.threads_per_page)
    except Http404:
        return redirect('new_threads')

    queryset = queryset.order_by('-start').prefetch_related(
        'forum')[pagination['start']:pagination['stop']]
    if settings.avatars_on_threads_list:
        queryset = queryset.prefetch_related('start_poster', 'last_poster')

    return render_to_response(
        'new_threads.html', {
            'items_total': items_total,
            'threads': Thread.objects.with_reads(queryset, request.user),
            'prefixes': ThreadPrefix.objects.all_prefixes(),
            'pagination': pagination,
        },
        context_instance=RequestContext(request))
Esempio n. 6
0
def forum_map(request):
    return render_to_response('forum_map.html',
                              {
                               'forums': Forum.objects.treelist(request.acl.forums,
                                                                Forum.objects.special_model('root'))
                              },
                              context_instance=RequestContext(request));
Esempio n. 7
0
def options(request):
    message = request.messages.get_message('usercp_options')
    if request.method == 'POST':
        form = UserForumOptionsForm(request.POST, request=request)
        if form.is_valid():
            request.user.hide_activity = form.cleaned_data['hide_activity']
            request.user.allow_pds = form.cleaned_data['allow_pds']
            request.user.receive_newsletters = form.cleaned_data['newsletters']
            request.user.timezone = form.cleaned_data['timezone']
            request.user.subscribe_start = form.cleaned_data['subscribe_start']
            request.user.subscribe_reply = form.cleaned_data['subscribe_reply']
            request.user.save(force_update=True)
            messages.success(request, _("Forum options have been changed."), 'usercp_options')
            return redirect(reverse('usercp'))
        message = Message(form.non_field_errors()[0], messages.ERROR)
    else:
        form = UserForumOptionsForm(request=request, initial={
                                                             'newsletters': request.user.receive_newsletters,
                                                             'hide_activity': request.user.hide_activity,
                                                             'allow_pds': request.user.allow_pds,
                                                             'timezone': request.user.timezone,
                                                             'subscribe_start': request.user.subscribe_start,
                                                             'subscribe_reply': request.user.subscribe_reply,
                                                             })

    return render_to_response('usercp/options.html',
                              context_instance=RequestContext(request, {
                                  'message': message,
                                  'tab': 'options',
                                  'form': form}));
Esempio n. 8
0
    def call(self, **kwargs):
        result = self.request.session.get('search_results')
        if not result:
            return error404(self.request, _("No search results were found."))

        items = result['search_results']
        items_total = len(items);
        try:
            pagination = make_pagination(kwargs.get('page', 0), items_total, 12)
        except Http404:
            return redirect(reverse('search_results'))

        return render_to_response('search/results.html',
                                  {
                                   'search_in': result.get('search_in'),
                                   'search_route': result.get('search_route'),
                                   'search_query': result['search_query'],
                                   'search_author': result.get('search_author'),
                                   'search_thread_titles': result.get('search_thread_titles'),
                                   'search_thread': result.get('search_thread'),
                                   'results': Post.objects.filter(id__in=items).select_related('forum', 'thread', 'user').order_by('-pk')[pagination['start']:pagination['stop']],
                                   'items_total': items_total,
                                   'pagination': pagination,
                                  },
                                  context_instance=RequestContext(self.request))
Esempio n. 9
0
 def thread_action_move(self):
     message = None
     if self.request.POST.get('do') == 'move':
         form = MoveThreadsForm(self.request.POST, request=self.request, forum=self.forum)
         if form.is_valid():
             new_forum = form.cleaned_data['new_forum']
             self.thread.move_to(new_forum)
             self.thread.save(force_update=True)
             self.thread.set_checkpoint(self.request, 'moved', forum=self.forum)
             self.forum.sync()
             self.forum.save(force_update=True)
             new_forum.sync()
             new_forum.save(force_update=True)
             messages.success(self.request, _('Thread has been moved to "%(forum)s".') % {'forum': new_forum.name}, 'threads')
             return None
         message = Message(form.non_field_errors()[0], messages.ERROR)
     else:
         form = MoveThreadsForm(request=self.request, forum=self.forum)
     return render_to_response('%ss/move_thread.html' % self.type_prefix,
                               {
                               'type_prefix': self.type_prefix,
                               'message': message,
                               'forum': self.forum,
                               'parents': self.parents,
                               'thread': self.thread,
                               'form': form,
                               },
                               context_instance=RequestContext(self.request));
Esempio n. 10
0
def crop(request, upload=False):
    if upload and (not request.user.avatar_temp or not 'upload' in settings.avatars_types):
        return error404(request)

    if not upload and request.user.avatar_type != 'upload':
        messages.error(request, _("Crop Avatar option is avaiable only when you use uploaded image as your avatar."), 'usercp_avatar')
        return redirect(reverse('usercp_avatar'))

    message = request.messages.get_message('usercp_avatar')
    if request.method == 'POST':
        if request.csrf.request_secure(request):
            try:
                image_path = settings.MEDIA_ROOT + 'avatars/'
                if upload:
                    source = Image.open(image_path + request.user.avatar_temp)
                else:
                    source = Image.open(image_path + request.user.avatar_original)
                width, height = source.size

                aspect = float(width) / float(request.POST['crop_b'])
                crop_x = int(aspect * float(request.POST['crop_x']))
                crop_y = int(aspect * float(request.POST['crop_y']))
                crop_w = int(aspect * float(request.POST['crop_w']))
                crop = source.crop((crop_x, crop_y, crop_x + crop_w, crop_y + crop_w))

                if upload:
                    image_name, image_extension = path(request.user.avatar_temp).splitext()
                else:
                    image_name, image_extension = path(request.user.avatar_original).splitext()
                image_name = '%s_%s%s' % (request.user.pk, random_string(8), image_extension)
                resizeimage(crop, settings.AVATAR_SIZES[0], image_path + image_name, info=source.info, format=source.format)
                for size in settings.AVATAR_SIZES[1:]:
                    resizeimage(crop, size, image_path + str(size) + '_' + image_name, info=source.info, format=source.format)

                request.user.delete_avatar_image()
                if upload:
                    request.user.delete_avatar_original()
                    request.user.avatar_type = 'upload'
                    request.user.avatar_original = '%s_org_%s%s' % (request.user.pk, random_string(8), image_extension)
                    source.save(image_path + request.user.avatar_original)
                request.user.delete_avatar_temp()
                request.user.avatar_image = image_name
                request.user.avatar_crop = [str(float(request.POST[x])) for x in ('crop_x', 'crop_y', 'crop_w')]
                request.user.save(force_update=True)
                messages.success(request, _("Your avatar has been cropped."), 'usercp_avatar')
                return redirect(reverse('usercp_avatar'))
            except Exception:
                message = Message(_("Form contains errors."), messages.ERROR)
        else:
            message = Message(_("Request authorisation is invalid."), messages.ERROR)


    return render_to_response('usercp/avatar_crop.html',
                              context_instance=RequestContext(request, {
                                  'message': message,
                                  'after_upload': upload,
                                  'avatar_size': settings.AVATAR_SIZES[0],
                                  'avatar_crop': request.user.avatar_crop if not upload else None,
                                  'source': 'avatars/%s' % (request.user.avatar_temp if upload else request.user.avatar_original),
                                  'tab': 'avatar'}));
Esempio n. 11
0
def posts(request, user, page=0):
    queryset = user.post_set.filter(forum_id__in=Forum.objects.readable_forums(request.acl)).filter(deleted=False).filter(moderated=False)
    count = queryset.count()
    try:
        pagination = make_pagination(page, count, 12)
    except Http404:
        return redirect(reverse('user_posts', kwargs={'user': user.id, 'username': user.username_slug}))
    
    cache_key = 'user_profile_posts_graph_%s' % user.pk
    graph = cache.get(cache_key, 'nada')
    if graph == 'nada':
        if user.posts:
            graph = user.timeline(queryset.filter(date__gte=timezone.now()-timedelta(days=100)))
        else:
            graph = [0 for x in range(100)]
        cache.set(cache_key, graph, 14400)

    return render_to_response('profiles/posts.html',
                              context_instance=RequestContext(request, {
                                  'profile': user,
                                  'tab': 'posts',
                                  'graph_max': max(graph),
                                  'graph': (str(i) for i in graph),
                                  'items_total': count,
                                  'items': queryset.select_related('thread', 'forum').order_by('-id')[pagination['start']:pagination['stop']],
                                  'pagination': pagination,
                                  }));
Esempio n. 12
0
def details(request, user):
    return render_to_response('profiles/details.html',
                              context_instance=RequestContext(
                                  request, {
                                      'profile': user,
                                      'tab': 'details',
                                  }))
Esempio n. 13
0
def form(request):
    message = None
    if request.method == 'POST':
        form = UserSendActivationMailForm(request.POST, request=request)
        if form.is_valid():
            user = form.found_user
            user_ban = Ban.objects.check_ban(username=user.username, email=user.email)

            if user_ban:
                return error_banned(request, user, user_ban)

            if user.activation == User.ACTIVATION_NONE:
                return redirect_message(request, messages.INFO, _("%(username)s, your account is already active.") % {'username': user.username})

            if user.activation == User.ACTIVATION_ADMIN:
                return redirect_message(request, messages.INFO, _("%(username)s, only board administrator can activate your account.") % {'username': user.username})

            user.email_user(
                            request,
                            'users/activation/resend',
                            _("Account Activation"),
                            )
            return redirect_message(request, messages.SUCCESS, _("%(username)s, e-mail containing new activation link has been sent to %(email)s.") % {'username': user.username, 'email': user.email})
        else:
            message = Message(form.non_field_errors()[0], messages.ERROR)
    else:
        form = UserSendActivationMailForm(request=request)
    return render_to_response('resend_activation.html',
                              {
                               'message': message,
                               'form': form,
                              },
                              context_instance=RequestContext(request));
Esempio n. 14
0
 def action_move(self, ids):
     threads = []
     for thread in self.threads:
         if thread.pk in ids:
             threads.append(thread)
     if self.request.POST.get('origin') == 'move_form':
         form = MoveThreadsForm(self.request.POST, request=self.request, forum=self.forum)
         if form.is_valid():
             new_forum = form.cleaned_data['new_forum']
             for thread in threads:
                 thread.move_to(new_forum)
                 thread.save(force_update=True)
                 thread.set_checkpoint(self.request, 'moved', forum=self.forum)
                 thread.update_current_dates()
             new_forum.sync()
             new_forum.save(force_update=True)
             self.forum.sync()
             self.forum.save(force_update=True)
             messages.success(self.request, _('Selected threads have been moved to "%(forum)s".') % {'forum': new_forum.name}, 'threads')
             return None
         self.message = Message(form.non_field_errors()[0], messages.ERROR)
     else:
         form = MoveThreadsForm(request=self.request, forum=self.forum)
     return render_to_response('%ss/move_threads.html' % self.type_prefix,
                               {
                               'type_prefix': self.type_prefix,
                               'search_in': self.search_in,
                               'message': self.message,
                               'forum': self.forum,
                               'parents': self.parents,
                               'threads': threads,
                               'form': form,
                               },
                               context_instance=RequestContext(self.request));
Esempio n. 15
0
    def dispatch(self, request, **kwargs):
        try:
            next = self.post.change_set.filter(id__gt=self.change.pk)[:1][0]
            compare_to = next.post_content
        except IndexError:
            next = None
            compare_to = self.post.post
        try:
            prev = self.post.change_set.filter(id__lt=self.change.pk).order_by('-id')[:1][0]
        except IndexError:
            prev = None
		
        self.forum.closed = self.proxy.closed
        
        return render_to_response('%ss/changelog_diff.html' % self.type_prefix,
                                  self._template_vars({
                                        'forum': self.forum,
                                        'parents': self.parents,
                                        'thread': self.thread,
                                        'post': self.post,
                                        'change': self.change,
                                        'next': next,
                                        'prev': prev,
                                        'message': request.messages.get_message('changelog'),
                                        'l': 1,
                                        'diff': difflib.ndiff(self.change.post_content.splitlines(), compare_to.splitlines()),
                                      }),
                                  context_instance=RequestContext(request))
Esempio n. 16
0
def form(request):
    message = None

    if request.method == 'POST':
        form = UserResetPasswordForm(request.POST, request=request)

        if form.is_valid():
            user = form.found_user
            user_ban = Ban.objects.check_ban(username=user.username, email=user.email)

            if user_ban:
                return error_banned(request, user, user_ban)
            elif user.activation != User.ACTIVATION_NONE:
                return redirect_message(request, messages.INFO, _("%(username)s, your account has to be activated in order for you to be able to request new password.") % {'username': user.username})

            user.token = random_string(12)
            user.save(force_update=True)
            user.email_user(
                            request,
                            'users/password/confirm',
                            _("Confirm New Password Request")
                            )

            return redirect_message(request, messages.INFO, _("%(username)s, new password request confirmation has been sent to %(email)s.") % {'username': user.username, 'email': user.email})
        else:
            message = Message(form.non_field_errors()[0], messages.ERROR)
    else:
        form = UserResetPasswordForm(request=request)
    return render_to_response('reset_password.html',
                              {
                              'message': message,
                              'form': form,
                              },
                              context_instance=RequestContext(request));
Esempio n. 17
0
 def decorator(*args, **kwargs):
     request = args[0]
     if request.user.avatar_ban:
         return render_to_response('usercp/avatar_banned.html',
                                   context_instance=RequestContext(request, {
                                       'tab': 'avatar'}));
     return f(*args, **kwargs)
Esempio n. 18
0
 def decorator(*args, **kwargs):
     request = args[0]
     if request.user.avatar_ban:
         return render_to_response('usercp/avatar_banned.html',
                                   context_instance=RequestContext(
                                       request, {'tab': 'avatar'}))
     return f(*args, **kwargs)
Esempio n. 19
0
 def thread_action_move(self):
     message = None
     if self.request.POST.get('do') == 'move':
         form = MoveThreadsForm(self.request.POST,
                                request=self.request,
                                forum=self.forum)
         if form.is_valid():
             new_forum = form.cleaned_data['new_forum']
             self.thread.move_to(new_forum)
             self.thread.save(force_update=True)
             self.thread.set_checkpoint(self.request,
                                        'moved',
                                        forum=self.forum)
             self.forum.sync()
             self.forum.save(force_update=True)
             new_forum.sync()
             new_forum.save(force_update=True)
             messages.success(
                 self.request,
                 _('Thread has been moved to "%(forum)s".') %
                 {'forum': new_forum.name}, 'threads')
             return None
         message = Message(form.non_field_errors()[0], messages.ERROR)
     else:
         form = MoveThreadsForm(request=self.request, forum=self.forum)
     return render_to_response('%ss/move_thread.html' % self.type_prefix, {
         'type_prefix': self.type_prefix,
         'message': message,
         'forum': self.forum,
         'parents': self.parents,
         'thread': self.thread,
         'form': form,
     },
                               context_instance=RequestContext(
                                   self.request))
Esempio n. 20
0
def settings(request, group_id=None, group_slug=None):
    # Load groups and find selected group
    settings_groups = SettingsGroup.objects.all().order_by('key')
    if not group_id:
        active_group = settings_groups[0]
        group_id = active_group.pk
    else:
        group_id = int(group_id)
        for group in settings_groups:
            if group.pk == group_id:
                active_group = group
                break
        else:
            return error404(request, _('Requested settings group could not be found.'))

    # Load selected group settings and turn them into form
    group_settings = Setting.objects.filter(group=active_group).order_by('position')
    last_fieldset = (None, [])
    group_form = {'fieldsets': []}
    for setting in group_settings:
        # New field subgroup?
        if setting.separator and last_fieldset[0] != setting.separator:
            if last_fieldset[0]:
                group_form['fieldsets'].append(last_fieldset)
            last_fieldset = (_(setting.separator), [])
        last_fieldset[1].append(setting.pk)
        group_form[setting.pk] = setting.get_field()
    group_form['fieldsets'].append(last_fieldset)
    SettingsGroupForm = type('SettingsGroupForm', (Form,), group_form)

    #Submit form
    message = messages.get_message(request, 'admin_settings')
    if request.method == 'POST':
        form = SettingsGroupForm(request.POST, request=request)
        if form.is_valid():
            for setting in form.cleaned_data.keys():
                misago_settings[setting] = form.cleaned_data[setting]
            cache.delete('settings')
            messages.success(request, _('Configuration has been changed.'), 'admin_settings')
            return redirect(reverse('admin_settings', kwargs={
                                                       'group_id': active_group.pk,
                                                       'group_slug': active_group.key,
                                                       }))
        else:
            message = Message(form.non_field_errors()[0], messages.ERROR)
    else:
        form = SettingsGroupForm(request=request)

    # Display settings group form
    return render_to_response('settings/settings.html',
                              {
                              'message': message,
                              'groups': settings_groups,
                              'active_group': active_group,
                              'search_form': SearchForm(request=request),
                              'form': FormIterator(form),
                              'raw_form': form,
                              },
                              context_instance=RequestContext(request));
Esempio n. 21
0
def avatar(request):
    message = request.messages.get_message('usercp_avatar')
    return render_to_response('usercp/avatar.html',
                              context_instance=RequestContext(
                                  request, {
                                      'message': message,
                                      'tab': 'avatar'
                                  }))
Esempio n. 22
0
    def __call__(self, request, target=None, slug=None):
        self.request = request

        # Fetch target
        model = None
        if target:
            model = self.get_and_validate_target(target)
            self.original_name = self.get_target_name(model)
            if not model:
                return redirect(self.get_fallback_link())
        original_model = model

        # Set filter
        users = model.make_queryset()
        total_users = users.count()

        if not total_users:
            messages.error(request, _('Policy "%(name)s" does not apply to any users.') % {'name': model.name}, self.admin.id)
            return redirect(reverse('admin_prune_users'))

        message = None
        if request.method == 'POST':
            deleted = 0
            if request.csrf.request_secure(request):
                for user in users.iterator():
                    if user.is_protected():
                        messages.info(request, _('User "%(name)s" is protected and was not deleted.') % {'name': user.username}, self.admin.id)
                    else:
                        user.delete()
                        deleted += 1
                if deleted:
                    messages.success(request, ungettext(
                                                        'One user has been deleted.',
                                                        '%(deleted)d users have been deleted.',
                                                        deleted
                                                        ) % {'deleted': deleted}, self.admin.id)
                    User.objects.resync_monitor()
                else:
                    messages.info(request, _("No users have been deleted."), self.admin.id)
                return redirect(reverse('admin_prune_users'))
            else:
                message = Message(_("Request authorization is invalid. Please resubmit your form."), messages.ERROR)

        return render_to_response(self.get_template(),
                                  {
                                  'admin': self.admin,
                                  'action': self,
                                  'request': request,
                                  'link': self.get_link(model),
                                  'fallback': self.get_fallback_link(),
                                  'messages': messages.get_messages(request, self.admin.id),
                                  'message': message,
                                  'tabbed': self.tabbed,
                                  'total_users': total_users,
                                  'target': self.get_target_name(original_model),
                                  'target_model': original_model,
                                  },
                                  context_instance=RequestContext(request));
Esempio n. 23
0
def graph(request, model, date_start, date_end, precision):
    """
    Generate fancy graph for model and stuff
    """
    if date_start == date_end:
        # Bad dates
        raise error404(RequestContext)

    # Turn stuff into datetime's
    date_start = datetime.strptime(date_start, "%Y-%m-%d")
    date_end = datetime.strptime(date_end, "%Y-%m-%d")

    statistics_providers = []
    models_map = {}
    for model_obj in models.get_models():
        try:
            getattr(model_obj.objects, "filter_stats")
            statistics_providers.append((str(model_obj.__name__).lower(), model_obj.statistics_name))
            models_map[str(model_obj.__name__).lower()] = model_obj
        except AttributeError:
            pass

    if not statistics_providers:
        # Like before, q.q on lack of models
        return render_to_response("stats/not_available.html", context_instance=RequestContext(request))

    if not model in models_map or check_dates(date_start, date_end, precision):
        # Bad model name or graph data!
        raise error404(request)

    form = GenerateStatisticsForm(
        provider_choices=statistics_providers,
        request=request,
        initial={"provider_model": model, "date_start": date_start, "date_end": date_end, "stats_precision": precision},
    )
    return render_to_response(
        "stats/graph.html",
        {
            "title": models_map[model].statistics_name,
            "graph": build_graph(models_map[model], date_start, date_end, precision),
            "form": form,
            "message": request.messages.get_message("admin_stats"),
        },
        context_instance=RequestContext(request),
    )
Esempio n. 24
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.parents = []
        self.ignored = False
        self.watcher = False
        self.message = request.messages.get_message("threads")
        try:
            self._type_available()
            self.fetch_thread()
            self.check_forum_type()
            self._check_permissions()
            response = self.fetch_posts()
            if response:
                return response
            self.make_thread_form()
            if self.thread_form:
                response = self.handle_thread_form()
                if response:
                    return response
            self.make_posts_form()
            if self.posts_form:
                response = self.handle_posts_form()
                if response:
                    return response
        except (Forum.DoesNotExist, Thread.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        # Merge proxy into forum
        self.forum.closed = self.proxy.closed

        return render_to_response(
            "%ss/thread.html" % self.type_prefix,
            self._template_vars(
                {
                    "message": self.message,
                    "forum": self.forum,
                    "parents": self.parents,
                    "thread": self.thread,
                    "is_read": self.tracker.is_read(self.thread),
                    "count": self.count,
                    "posts": self.posts,
                    "ignored_posts": self.ignored,
                    "watcher": self.watcher,
                    "pagination": self.pagination,
                    "emojis": emojis(),
                    "quick_reply": QuickReplyForm(request=request),
                    "thread_form": self.thread_form or None,
                    "posts_form": self.posts_form or None,
                }
            ),
            context_instance=RequestContext(request),
        )
Esempio n. 25
0
 def response(self):
     return render_to_response('%ss/details.html' % self.type_prefix,
                               self._template_vars({
                                     'forum': self.forum,
                                     'parents': self.parents,
                                     'thread': self.thread,
                                     'post': self.post,
                                   }),
                               context_instance=RequestContext(self.request))
Esempio n. 26
0
def graph(request, model, date_start, date_end, precision):
    """
    Generate fancy graph for model and stuff
    """
    if date_start == date_end:
        # Bad dates
        raise error404(RequestContext)

    # Turn stuff into datetime's
    date_start = datetime.strptime(date_start, '%Y-%m-%d')
    date_end = datetime.strptime(date_end, '%Y-%m-%d')


    statistics_providers = []
    models_map = {}
    for model_obj in models.get_models():
        try:
            getattr(model_obj.objects, 'filter_stats')
            statistics_providers.append((str(model_obj.__name__).lower(), model_obj.statistics_name))
            models_map[str(model_obj.__name__).lower()] = model_obj
        except AttributeError:
            pass

    if not statistics_providers:
        # Like before, q.q on lack of models
        return render_to_response('stats/not_available.html',
                                  context_instance=RequestContext(request));

    if not model in models_map or check_dates(date_start, date_end, precision):
        # Bad model name or graph data!
        raise error404(request)

    form = GenerateStatisticsForm(
                                  provider_choices=statistics_providers,
                                  request=request,
                                  initial={'provider_model': model, 'date_start': date_start, 'date_end': date_end, 'stats_precision': precision})
    return render_to_response('stats/graph.html',
                              {
                              'title': models_map[model].statistics_name,
                              'graph': build_graph(models_map[model], date_start, date_end, precision),
                              'form': form,
                              'message': request.messages.get_message('admin_stats'),
                              },
                              context_instance=RequestContext(request));
Esempio n. 27
0
 def dispatch(self, request, **kwargs):
     return render_to_response('%ss/changelog.html' % self.type_prefix,
                               self._template_vars({
                                     'forum': self.forum,
                                     'parents': self.parents,
                                     'thread': self.thread,
                                     'post': self.post,
                                     'edits': self.post.change_set.prefetch_related('user').order_by('-id')
                                   }),
                               context_instance=RequestContext(request))
Esempio n. 28
0
def index(request):
    return render_to_response('index.html',
                              {
                               'users': monitor['users'],
                               'users_inactive': monitor['users_inactive'],
                               'threads': monitor['threads'],
                               'posts': monitor['posts'],
                               'admins': Session.objects.filter(user__isnull=False).filter(admin=1).order_by('user__username_slug').select_related('user'),
                              },
                              context_instance=RequestContext(request));
Esempio n. 29
0
 def response(self):
     return render_to_response('%ss/details.html' % self.type_prefix,
                               self._template_vars({
                                   'forum': self.forum,
                                   'parents': self.parents,
                                   'thread': self.thread,
                                   'post': self.post,
                               }),
                               context_instance=RequestContext(
                                   self.request))
Esempio n. 30
0
def send(request, target, token):
    try:
        newsletter = Newsletter.objects.get(pk=target, token=token)

        # Build recipients queryset
        recipients = User.objects
        if newsletter.ranks.all():
            recipients = recipients.filter(rank__in=[x.pk for x in newsletter.ranks.all()])
        if not newsletter.ignore_subscriptions:
            recipients = recipients.filter(receive_newsletters=1)

        recipients_total = recipients.count()
        if recipients_total < 1:
            messages.error(request, _('No recipients for newsletter "%(newsletter)s" could be found.') % {'newsletter': newsletter.name}, 'newsletters')
            return redirect(reverse('admin_newsletters'))

        for user in recipients.all()[newsletter.progress:(newsletter.progress + newsletter.step_size)]:
            tokens = {
              '{{ board_name }}': settings.board_name,
              '{{ username }}': user.username,
              '{{ user_link }}': django_reverse('user', kwargs={'username': user.username_slug, 'user': user.pk}),
              '{{ board_link }}': settings.BOARD_ADDRESS,
            }
            subject = newsletter.parse_name(tokens)
            user.email_user(request, 'users/newsletter', subject, {
                                                                'newsletter': newsletter,
                                                                'subject': subject,
                                                                'content_html': newsletter.parse_html(tokens),
                                                                'content_plain': newsletter.parse_plain(tokens),
                                                                })
            newsletter.progress += 1
        newsletter.generate_token()
        newsletter.save(force_update=True)

        if newsletter.progress >= recipients_total:
            newsletter.progress = 0
            newsletter.save(force_update=True)
            messages.success(request, _('Newsletter "%(newsletter)s" has been sent.') % {'newsletter': newsletter.name}, 'newsletters')
            return redirect(reverse('admin_newsletters'))

        # Render Progress
        response = render_to_response('processing.html',
                                      {
                                      'task_name': _('Sending Newsletter'),
                                      'target_name': newsletter.name,
                                      'message': _('Sent to %(progress)s from %(total)s users') % {'progress': newsletter.progress, 'total': recipients_total},
                                      'progress': newsletter.progress * 100 / recipients_total,
                                      'cancel_link': reverse('admin_newsletters'),
                                      },
                                      context_instance=RequestContext(request));
        response['refresh'] = '2;url=%s' % reverse('admin_newsletters_send', newsletter)
        return response
    except Newsletter.DoesNotExist:
        messages.error(request, _('Requested Newsletter could not be found.'), 'newsletters')
        return redirect(reverse('admin_newsletters'))
Esempio n. 31
0
def username(request):
    if not request.acl.usercp.show_username_change():
        return error404(request)

    changes_left = request.acl.usercp.changes_left(request.user)
    next_change = None
    if request.acl.usercp.changes_expire() and not changes_left:
        next_change = request.user.namechanges.filter(
                                                      date__gte=timezone.now() - timedelta(days=request.acl.usercp.acl['changes_expire']),
                                                      ).order_by('-date')[0]
        next_change = next_change.date + timedelta(days=request.acl.usercp.acl['changes_expire'])

    message = request.messages.get_message('usercp_username')
    if request.method == 'POST':
        if not changes_left:
            message = Message(_("You have exceeded the maximum number of name changes."), messages.ERROR)
            form = UsernameChangeForm(request=request)
        else:
            org_username = request.user.username
            form = UsernameChangeForm(request.POST, request=request)
            if form.is_valid():
                request.user.set_username(form.cleaned_data['username'])
                request.user.save(force_update=True)
                request.user.sync_username()
                request.user.namechanges.create(date=timezone.now(), old_username=org_username)
                messages.success(request, _("Your username has been changed."), 'usercp_username')
                # Alert followers of namechange
                alert_time = timezone.now()
                bulk_alerts = []
                alerted_users = []
                for follower in request.user.follows_set.iterator():
                    alerted_users.append(follower.pk)
                    alert = Alert(user=follower, message=ugettext_lazy("User that you are following, %(username)s, has changed his name to %(newname)s").message, date=alert_time)
                    alert.strong('username', org_username)
                    alert.profile('newname', request.user)
                    alert.hydrate()
                    bulk_alerts.append(alert)
                if bulk_alerts:
                    Alert.objects.bulk_create(bulk_alerts)
                    User.objects.filter(id__in=alerted_users).update(alerts=F('alerts') + 1)
                # Hop back
                return redirect(reverse('usercp_username'))
            message = Message(form.non_field_errors()[0], messages.ERROR)
    else:
        form = UsernameChangeForm(request=request)

    return render_to_response('usercp/username.html',
                              context_instance=RequestContext(request, {
                                  'message': message,
                                  'changes_left': changes_left,
                                  'form': form,
                                  'next_change': next_change,
                                  'changes_history': request.user.namechanges.order_by('-date')[:10],
                                  'tab': 'username'}));
Esempio n. 32
0
 def response(self):
     return render_to_response('%ss/karmas.html' % self.type_prefix,
                               self._template_vars({
                                     'forum': self.forum,
                                     'parents': self.parents,
                                     'thread': self.thread,
                                     'post': self.post,
                                     'upvotes': self.post.karma_set.filter(score=1),
                                     'downvotes': self.post.karma_set.filter(score=-1),
                                   }),
                               context_instance=RequestContext(self.request))
Esempio n. 33
0
def resync_forums(request, forum=0, progress=0):
    progress = int(progress)
    forums = request.session.get('sync_forums')
    if not forums:
        messages.info(request, _('No forums to resynchronize.'), 'forums')
        return redirect(reverse('admin_forums'))
    try:
        if not forum:
            forum = request.session['sync_forums'].pop()
        forum = Forum.objects.get(id=forum)
    except Forum.DoesNotExist:
        del request.session['sync_forums']
        messages.error(request,
                       _('Forum for resynchronization does not exist.'),
                       'forums')
        return redirect(reverse('admin_forums'))

    # Sync 50 threads
    threads_total = forum.thread_set.count()
    for thread in forum.thread_set.all()[progress:(progress + 1)]:
        thread.sync()
        thread.save(force_update=True)
        progress += 1

    if not threads_total:
        return redirect(django_reverse('admin_forums_resync'))

    # Render Progress
    response = render_to_response('processing.html', {
        'task_name': _('Resynchronizing Forums'),
        'target_name': forum.name,
        'message': _('Resynchronized %(progress)s from %(total)s threads') % {
            'progress': progress,
            'total': threads_total
        },
        'progress': progress * 100 / threads_total,
        'cancel_link': reverse('admin_forums'),
    },
                                  context_instance=RequestContext(request))

    # Redirect where to?
    if progress >= threads_total:
        forum.sync()
        forum.save(force_update=True)
        response['refresh'] = '2;url=%s' % django_reverse(
            'admin_forums_resync')
    else:
        response['refresh'] = '2;url=%s' % django_reverse(
            'admin_forums_resync',
            kwargs={
                'forum': forum.pk,
                'progress': progress
            })
    return response
Esempio n. 34
0
 def post_action_split(self, ids):
     for id in ids:
         if id == self.thread.start_post_id:
             raise forms.ValidationError(_("You cannot split first post from thread."))
     message = None
     if self.request.POST.get("do") == "split":
         form = SplitThreadForm(self.request.POST, request=self.request)
         if form.is_valid():
             new_thread = Thread()
             new_thread.forum = form.cleaned_data["thread_forum"]
             new_thread.name = form.cleaned_data["thread_name"]
             new_thread.slug = slugify(form.cleaned_data["thread_name"])
             new_thread.start = timezone.now()
             new_thread.last = timezone.now()
             new_thread.start_poster_name = "n"
             new_thread.start_poster_slug = "n"
             new_thread.last_poster_name = "n"
             new_thread.last_poster_slug = "n"
             new_thread.save(force_insert=True)
             for post in self.posts:
                 if post.pk in ids:
                     post.move_to(new_thread)
                     post.save(force_update=True)
             new_thread.sync()
             new_thread.save(force_update=True)
             self.thread.sync()
             self.thread.save(force_update=True)
             self.forum.sync()
             self.forum.save(force_update=True)
             if new_thread.forum != self.forum:
                 new_thread.forum.sync()
                 new_thread.forum.save(force_update=True)
             messages.success(self.request, _("Selected posts have been split to new thread."), "threads")
             return redirect(reverse(self.type_prefix, kwargs={"thread": new_thread.pk, "slug": new_thread.slug}))
         message = Message(form.non_field_errors()[0], messages.ERROR)
     else:
         form = SplitThreadForm(
             request=self.request,
             initial={"thread_name": _("[Split] %s") % self.thread.name, "thread_forum": self.forum},
         )
     return render_to_response(
         "%ss/split.html" % self.type_prefix,
         {
             "type_prefix": self.type_prefix,
             "message": message,
             "forum": self.forum,
             "parents": self.parents,
             "thread": self.thread,
             "posts": ids,
             "form": form,
         },
         context_instance=RequestContext(self.request),
     )
Esempio n. 35
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.parents = []
        self.ignored = False
        self.watcher = False
        self.message = request.messages.get_message('threads')
        try:
            self._type_available()
            self.fetch_thread()
            self.check_forum_type()
            self._check_permissions()
            response = self.fetch_posts()
            if response:
                return response
            self.make_thread_form()
            if self.thread_form:
                response = self.handle_thread_form()
                if response:
                    return response
            self.make_posts_form()
            if self.posts_form:
                response = self.handle_posts_form()
                if response:
                    return response
        except (Forum.DoesNotExist, Thread.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        # Merge proxy into forum
        self.forum.closed = self.proxy.closed

        return render_to_response('%ss/thread.html' % self.type_prefix,
                                  self._template_vars({
                                        'message': self.message,
                                        'forum': self.forum,
                                        'parents': self.parents,
                                        'thread': self.thread,
                                        'is_read': self.tracker.is_read(self.thread),
                                        'count': self.count,
                                        'posts': self.posts,
                                        'ignored_posts': self.ignored,
                                        'watcher': self.watcher,
                                        'pagination': self.pagination,
                                        'emojis': emojis(),
                                        'quick_reply': QuickReplyForm(request=request),
                                        'thread_form': self.thread_form or None,
                                        'posts_form': self.posts_form or None,
                                      }),
                                  context_instance=RequestContext(request));
Esempio n. 36
0
def watched_threads(request, page=0, new=False):
    # Find mode and fetch threads
    readable_forums = Forum.objects.readable_forums(request.acl, True)
    starter_readable_forums = Forum.objects.starter_readable_forums(request.acl)

    if not readable_forums and not readable_forums:
        return error403(request, _("%(username), you cannot read any forums.") % {'username': request.user.username})

    private_threads_pk = Forum.objects.special_pk('private_threads')
    if not settings.enable_private_threads and private_threads_pk in readable_forums:
        readable_forums.remove(private_threads_pk)

    queryset = WatchedThread.objects.filter(user=request.user).filter(thread__moderated=False).filter(thread__deleted=False).select_related('thread')
    if starter_readable_forums and readable_forums:
        queryset = queryset.filter(Q(forum_id__in=readable_forums) | Q(forum_id__in=starter_readable_forums, starter_id=request.user.pk))
    elif starter_readable_forums:
        queryset = queryset.filter(starter_id__in=request.user.pk).filter(forum_id__in=starter_readable_forums)
    else:
        queryset = queryset.filter(forum_id__in=readable_forums)

    if settings.avatars_on_threads_list:
        queryset = queryset.prefetch_related('thread__last_poster')
    if new:
        queryset = queryset.filter(last_read__lt=F('thread__last'))
    count = queryset.count()
    try:
        pagination = make_pagination(page, count, settings.threads_per_page)
    except Http404:
        if new:
            return redirect(reverse('watched_threads_new'))
        return redirect(reverse('watched_threads'))
    queryset = queryset.order_by('-thread__last')
    if settings.threads_per_page < count:
        queryset = queryset[pagination['start']:pagination['stop']]
    queryset.prefetch_related('thread__forum', 'thread__start_poster', 'thread__last_poster')
    threads = []
    for thread in queryset:
        thread.thread.send_email = thread.email
        thread.thread.is_read = thread.thread.last <= thread.last_read
        threads.append(thread.thread)

    # Display page
    return render_to_response('watched.html',
                              {
                              'items_total': count,
                              'pagination': pagination,
                              'new': new,
                              'threads': threads,
                              'prefixes': ThreadPrefix.objects.all_prefixes(),
                              'message': request.messages.get_message('threads'),
                              },
                              context_instance=RequestContext(request))
Esempio n. 37
0
def gallery(request):
    if not 'gallery' in settings.avatars_types:
        return error404(request)

    allowed_avatars = []
    galleries = []
    for directory in path(
            settings.STATICFILES_DIRS[0]).joinpath('avatars').dirs():
        if directory[-7:] != '_locked' and directory[-8:] != '_default':
            gallery = {'name': directory[-7:], 'avatars': []}
            avatars = directory.files('*.gif')
            avatars += directory.files('*.jpg')
            avatars += directory.files('*.jpeg')
            avatars += directory.files('*.png')
            for item in avatars:
                gallery['avatars'].append('/'.join(path(item).splitall()[-2:]))
            galleries.append(gallery)
            allowed_avatars += gallery['avatars']

    if not allowed_avatars:
        messages.info(request,
                      _("No avatar galleries are available at the moment."),
                      'usercp_avatar')
        return redirect(reverse('usercp_avatar'))

    message = request.messages.get_message('usercp_avatar')
    if request.method == 'POST':
        if request.csrf.request_secure(request):
            new_avatar = request.POST.get('avatar_image')
            if new_avatar in allowed_avatars:
                request.user.delete_avatar()
                request.user.avatar_type = 'gallery'
                request.user.avatar_image = new_avatar
                request.user.save(force_update=True)
                messages.success(
                    request,
                    _("Your avatar has been changed to one from gallery."),
                    'usercp_avatar')
                return redirect(reverse('usercp_avatar'))
            message = Message(_("Selected Avatar is incorrect."),
                              messages.ERROR)
        else:
            message = Message(_("Request authorisation is invalid."),
                              messages.ERROR)

    return render_to_response('usercp/avatar_gallery.html',
                              context_instance=RequestContext(
                                  request, {
                                      'message': message,
                                      'galleries': galleries,
                                      'tab': 'avatar'
                                  }))
Esempio n. 38
0
 def render_to_response(self, template, form, context):
     context['search_route'] = self.search_route
     context['form'] = form
     for i in ('search_query', 'search_in', 'search_author', 'search_thread_titles'):
         if self.request.POST.get(i):
             context[i] = self.request.POST.get(i)
     try:
         context['search_thread'] = self.thread_clean
     except AttributeError:
         pass
     return render_to_response('search/%s.html' % template,
                               context,
                               context_instance=RequestContext(self.request))
Esempio n. 39
0
 def post_action_split(self, ids):
     for id in ids:
         if id == self.thread.start_post_id:
             raise forms.ValidationError(_("You cannot split first post from thread."))
     message = None
     if self.request.POST.get('do') == 'split':
         form = SplitThreadForm(self.request.POST, request=self.request)
         if form.is_valid():
             new_thread = Thread()
             new_thread.forum = form.cleaned_data['thread_forum']
             new_thread.name = form.cleaned_data['thread_name']
             new_thread.slug = slugify(form.cleaned_data['thread_name'])
             new_thread.start = timezone.now()
             new_thread.last = timezone.now()
             new_thread.start_poster_name = 'n'
             new_thread.start_poster_slug = 'n'
             new_thread.last_poster_name = 'n'
             new_thread.last_poster_slug = 'n'
             new_thread.save(force_insert=True)
             for post in self.posts:
                 if post.pk in ids:
                     post.move_to(new_thread)
                     post.save(force_update=True)
             new_thread.sync()
             new_thread.save(force_update=True)
             self.thread.sync()
             self.thread.save(force_update=True)
             self.forum.sync()
             self.forum.save(force_update=True)
             if new_thread.forum != self.forum:
                 new_thread.forum.sync()
                 new_thread.forum.save(force_update=True)
             messages.success(self.request, _("Selected posts have been split to new thread."), 'threads')
             return redirect(reverse(self.type_prefix, kwargs={'thread': new_thread.pk, 'slug': new_thread.slug}))
         message = Message(form.non_field_errors()[0], messages.ERROR)
     else:
         form = SplitThreadForm(request=self.request, initial={
                                                               'thread_name': _('[Split] %s') % self.thread.name,
                                                               'thread_forum': self.forum,
                                                               })
     return render_to_response('%ss/split.html' % self.type_prefix,
                               {
                               'type_prefix': self.type_prefix,
                               'message': message,
                               'forum': self.forum,
                               'parents': self.parents,
                               'thread': self.thread,
                               'posts': ids,
                               'form': form,
                               },
                               context_instance=RequestContext(self.request));
Esempio n. 40
0
def error_banned(request, user=None, ban=None):
    if not ban:
        ban = request.ban
    if request.is_ajax():
        return json_response(request, status=403, message=_("You are banned."))
    response = render_to_response('error403_banned.html', {
        'banned_user': user,
        'ban': ban,
        'hide_signin': True,
        'exception_response': True,
    },
                                  context_instance=RequestContext(request))
    response.status_code = 403
    return response
Esempio n. 41
0
    def __call__(self, request, **kwargs):
        self.request = request
        self.kwargs = kwargs
        self.pagination = {}
        self.parents = []
        self.threads = []
        self.message = request.messages.get_message('threads')
        try:
            self._type_available()
            self._fetch_forum()
            self._check_permissions()
            response = self.fetch_threads()
            if response:
                return response
            self.form = None
            self.make_form()
            if self.form:
                response = self.handle_form()
                if response:
                    return response
        except (Forum.DoesNotExist, Thread.DoesNotExist):
            return error404(request)
        except ACLError403 as e:
            return error403(request, unicode(e))
        except ACLError404 as e:
            return error404(request, unicode(e))

        # Merge proxy into forum
        self.forum.closed = self.proxy.closed

        return render_to_response('%ss/%s.html' %
                                  (self.type_prefix, self.template),
                                  self._template_vars({
                                      'message':
                                      self.message,
                                      'forum':
                                      self.forum,
                                      'parents':
                                      self.parents,
                                      'count':
                                      self.count,
                                      'list_form':
                                      self.form or None,
                                      'threads':
                                      self.threads,
                                      'pagination':
                                      self.pagination,
                                  }),
                                  context_instance=RequestContext(request))
Esempio n. 42
0
def index(request):
    return render_to_response('index.html', {
        'users':
        monitor['users'],
        'users_inactive':
        monitor['users_inactive'],
        'threads':
        monitor['threads'],
        'posts':
        monitor['posts'],
        'admins':
        Session.objects.filter(user__isnull=False).filter(
            admin=1).order_by('user__username_slug').select_related('user'),
    },
                              context_instance=RequestContext(request))
Esempio n. 43
0
def followers(request, user, page=0):
    queryset = user.follows_set.order_by('username_slug')
    count = queryset.count()
    try:
        pagination = make_pagination(page, count, 24)
    except Http404:
        return redirect(reverse('user_followers', kwargs={'user': user.id, 'username': user.username_slug}))
    
    return render_to_response('profiles/followers.html',
                              context_instance=RequestContext(request, {
                                  'profile': user,
                                  'tab': 'followers',
                                  'items_total': count,
                                  'items': queryset[pagination['start']:pagination['stop']],
                                  'pagination': pagination,}));
Esempio n. 44
0
 def render_to_response(self, template, form, context):
     context['search_route'] = self.search_route
     context['form'] = form
     for i in ('search_query', 'search_in', 'search_author',
               'search_thread_titles'):
         if self.request.POST.get(i):
             context[i] = self.request.POST.get(i)
     try:
         context['search_thread'] = self.thread_clean
     except AttributeError:
         pass
     return render_to_response('search/%s.html' % template,
                               context,
                               context_instance=RequestContext(
                                   self.request))
Esempio n. 45
0
def index(request):
    sessions_expiration = timezone.now() - timedelta(seconds=settings.online_counting_frequency)
    admin_sessions = Session.objects.filter(user__isnull=False).filter(admin=1)
    admin_sessions = admin_sessions.filter(last__gte=sessions_expiration)
    admin_sessions = admin_sessions.order_by('user__username_slug').select_related('user')

    return render_to_response('index.html',
                              {
                                  'users': monitor['users'],
                                  'users_inactive': monitor['users_inactive'],
                                  'threads': monitor['threads'],
                                  'posts': monitor['posts'],
                                  'admins': admin_sessions,
                              },
                              context_instance=RequestContext(request))
Esempio n. 46
0
 def post_action_move(self, ids):
     message = None
     if self.request.POST.get('do') == 'move':
         form = MovePostsForm(self.request.POST,
                              request=self.request,
                              thread=self.thread)
         if form.is_valid():
             thread = form.cleaned_data['thread_url']
             for post in self.posts:
                 if post.pk in ids:
                     post.move_to(thread)
                     post.save(force_update=True)
             if self.thread.post_set.count() == 0:
                 self.thread.delete()
             else:
                 self.thread.sync()
                 self.thread.save(force_update=True)
             thread.sync()
             thread.save(force_update=True)
             thread.forum.sync()
             thread.forum.save(force_update=True)
             if self.forum.pk != thread.forum.pk:
                 self.forum.sync()
                 self.forum.save(force_update=True)
             messages.success(
                 self.request,
                 _("Selected posts have been moved to new thread."),
                 'threads')
             return redirect(
                 reverse(self.type_prefix,
                         kwargs={
                             'thread': thread.pk,
                             'slug': thread.slug
                         }))
         message = Message(form.non_field_errors()[0], messages.ERROR)
     else:
         form = MovePostsForm(request=self.request)
     return render_to_response('%ss/move_posts.html' % self.type_prefix, {
         'type_prefix': self.type_prefix,
         'message': message,
         'forum': self.forum,
         'parents': self.parents,
         'thread': self.thread,
         'posts': ids,
         'form': form,
     },
                               context_instance=RequestContext(
                                   self.request))
Esempio n. 47
0
 def dispatch(self, request, **kwargs):
     return render_to_response(
         '%ss/changelog.html' % self.type_prefix,
         self._template_vars({
             'forum':
             self.forum,
             'parents':
             self.parents,
             'thread':
             self.thread,
             'post':
             self.post,
             'edits':
             self.post.change_set.prefetch_related('user').order_by('-id')
         }),
         context_instance=RequestContext(request))
Esempio n. 48
0
def settings_search(request):
    settings_groups = SettingsGroup.objects.all().order_by('key')
    message = None
    found_settings = []
    try:
        if request.method == 'POST' and request.csrf.request_secure(request):
            form = SearchForm(request.POST, request=request)
            if form.is_valid():
                # Start search
                search_strings = SearchQuery(form.cleaned_data['search_text'])

                # Loop over groups using our search query
                for setting in Setting.objects.all().order_by('setting'):
                    if (search_strings.search(_(setting.name)) or
                        (setting.description
                         and search_strings.search(_(setting.description)))
                            or (setting.value
                                and search_strings.search(setting.value))):
                        found_settings.append(setting)

                # Scream if nothing could be found
                if found_settings:
                    message = Message(
                        ungettext(
                            'One setting that matches search criteria has been found.',
                            '%(count)d settings that match search criteria have been found.',
                            len(found_settings)) % {
                                'count': len(found_settings),
                            }, messages.SUCCESS)
                else:
                    raise SearchException(
                        _('No settings that match search criteria have been found.'
                          ))
            else:
                raise SearchException(_('Search query is empty.'))
        else:
            raise SearchException(_('Search query is invalid.'))
    except SearchException as e:
        message = Message(unicode(e), messages.ERROR)
    return render_to_response('settings/search_results.html', {
        'message': message,
        'groups': settings_groups,
        'active_group': None,
        'found_settings': found_settings,
        'search_form': form,
    },
                              context_instance=RequestContext(request))
Esempio n. 49
0
def newsfeed(request):
    follows = []
    for user in request.user.follows.iterator():
        follows.append(user.pk)
    queryset = []
    if follows:
        queryset = Post.objects.filter(forum_id__in=Forum.objects.readable_forums(request.acl))
        queryset = queryset.filter(deleted=False).filter(moderated=False)
        queryset = queryset.filter(user_id__in=follows)
        queryset = queryset.prefetch_related('thread', 'forum', 'user').order_by('-id')
        queryset = queryset[:18]
    return render_to_response('newsfeed.html',
                              {
                              'follows': follows,
                              'posts': queryset,
                              },
                              context_instance=RequestContext(request))
Esempio n. 50
0
def posts(request, user, page=0):
    queryset = user.post_set.filter(
        forum_id__in=Forum.objects.readable_forums(request.acl)).filter(
            deleted=False).filter(moderated=False)
    count = queryset.count()
    try:
        pagination = make_pagination(page, count, 12)
    except Http404:
        return redirect(
            reverse('user_posts',
                    kwargs={
                        'user': user.id,
                        'username': user.username_slug
                    }))

    cache_key = 'user_profile_posts_graph_%s' % user.pk
    graph = cache.get(cache_key, 'nada')
    if graph == 'nada':
        if user.posts:
            graph = user.timeline(
                queryset.filter(date__gte=timezone.now() -
                                timedelta(days=100)))
        else:
            graph = [0 for x in range(100)]
        cache.set(cache_key, graph, 14400)

    return render_to_response(
        'profiles/posts.html',
        context_instance=RequestContext(
            request, {
                'profile':
                user,
                'tab':
                'posts',
                'graph_max':
                max(graph),
                'graph': (str(i) for i in graph),
                'items_total':
                count,
                'items':
                queryset.select_related('thread', 'forum').order_by('-id')
                [pagination['start']:pagination['stop']],
                'pagination':
                pagination,
            }))
Esempio n. 51
0
def form(request):
    message = None
    if request.method == 'POST':
        form = UserSendActivationMailForm(request.POST, request=request)
        if form.is_valid():
            user = form.found_user
            user_ban = Ban.objects.check_ban(username=user.username,
                                             email=user.email)

            if user_ban:
                return error_banned(request, user, user_ban)

            if user.activation == User.ACTIVATION_NONE:
                return redirect_message(
                    request, messages.INFO,
                    _("%(username)s, your account is already active.") %
                    {'username': user.username})

            if user.activation == User.ACTIVATION_ADMIN:
                return redirect_message(
                    request, messages.INFO,
                    _("%(username)s, only board administrator can activate your account."
                      ) % {'username': user.username})

            user.email_user(
                request,
                'users/activation/resend',
                _("Account Activation"),
            )
            return redirect_message(
                request, messages.SUCCESS,
                _("%(username)s, e-mail containing new activation link has been sent to %(email)s."
                  ) % {
                      'username': user.username,
                      'email': user.email
                  })
        else:
            message = Message(form.non_field_errors()[0], messages.ERROR)
    else:
        form = UserSendActivationMailForm(request=request)
    return render_to_response('resend_activation.html', {
        'message': message,
        'form': form,
    },
                              context_instance=RequestContext(request))
Esempio n. 52
0
 def response(self):
     return render_to_response('%ss/karmas.html' % self.type_prefix,
                               self._template_vars({
                                   'forum':
                                   self.forum,
                                   'parents':
                                   self.parents,
                                   'thread':
                                   self.thread,
                                   'post':
                                   self.post,
                                   'upvotes':
                                   self.post.karma_set.filter(score=1),
                                   'downvotes':
                                   self.post.karma_set.filter(score=-1),
                               }),
                               context_instance=RequestContext(
                                   self.request))
Esempio n. 53
0
def error_view(request, error, message=None):
    if message:
        message = unicode(message)
    if request.is_ajax():
        if not message:
            if error == 404:
                message = _("Requested page could not be loaded.")
            if error == 403:
                message = _("You don't have permission to see requested page.")
        return json_response(request, status=error, message=message)
    response = render_to_response(('error%s.html' % error), {
        'message': message,
        'hide_signin': True,
        'exception_response': True,
    },
                                  context_instance=RequestContext(request))
    response.status_code = error
    return response