Example #1
0
    def render(self, context):
        args = [arg.resolve(context) for arg in self.args]
        kwargs = dict([(smart_str(k, 'ascii'), v.resolve(context))
                       for k, v in self.kwargs.items()])

        url = ''
        try:
            url = sph_reverse(self.view_name, args=args, kwargs=kwargs)
        except NoReverseMatch as e:
            if settings.SETTINGS_MODULE:
                project_name = settings.SETTINGS_MODULE.split('.')[0]
                try:
                    url = sph_reverse(project_name + '.' + self.view_name,
                                      args=args,
                                      kwargs=kwargs)
                except NoReverseMatch:
                    if self.asvar is None:
                        # Re-raise the original exception, not the one with
                        # the path relative to the project. This makes a
                        # better error message.
                        raise e
            else:
                if self.asvar is None:
                    raise e

        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            return url
 def render(self, context):
     from django.core.urlresolvers import reverse, NoReverseMatch
     args = [arg.resolve(context) for arg in self.args]
     kwargs = dict([(smart_str(k,'ascii'), v.resolve(context))
                    for k, v in self.kwargs.items()])
     
     url = ''
     try:
         url = sph_reverse(self.view_name,
                           args=args, kwargs=kwargs)
     except NoReverseMatch, e:
         if settings.SETTINGS_MODULE:
             project_name = settings.SETTINGS_MODULE.split('.')[0]
             try:
                 url = sph_reverse(project_name + '.' + self.view_name,
                                    args=args, kwargs=kwargs)
             except NoReverseMatch:
                 if self.asvar is None:
                     # Re-raise the original exception, not the one with
                     # the path relative to the project. This makes a
                     # better error message.
                     raise e
         else:
             if self.asvar is None:
                 raise e
Example #3
0
def register(
        request,
        group=None,
        frm=None,
        register_template_name='sphene/community/register.html',
        email_sent_template_name='sphene/community/register_emailsent.html'):

    if request.method == 'POST':
        form = RegisterEmailAddress(request.POST)
        if form.is_valid():
            regdata = form.cleaned_data
            email_address = regdata['email_address']
            if not group:
                subject = _(u'Email verification required')
            else:
                subject = _(
                    u'Email verification required for site %(site_name)s') % {
                        'site_name': group.get_name()
                    }
            validationcode = cryptString(settings.SECRET_KEY, email_address)
            if frm:
                mail_context_path = sph_reverse(
                    'sphene.community.views.register_hash', (), {
                        'emailHash': validationcode,
                    }).split('community')[1]
            else:
                mail_context_path = sph_reverse(
                    'sphene.community.views.register_hash', (), {
                        'emailHash': validationcode,
                    })

            mail_context = RequestContext(
                request, {
                    'email': email_address,
                    'baseurl': group.baseurl,
                    'path': mail_context_path,
                    'validationcode': validationcode,
                    'group': group,
                })
            text_part = loader.get_template('sphene/community/accounts/account_verification_email.txt') \
                .render(mail_context)
            html_part = loader.get_template('sphene/community/accounts/account_verification_email.html') \
                .render(mail_context)

            msg = EmailMultiAlternatives(subject, text_part, None,
                                         [email_address])
            msg.attach_alternative(html_part, "text/html")
            msg.send()

            return render_to_response(email_sent_template_name, {
                'email': email_address,
            },
                                      context_instance=RequestContext(request))
        pass
    else:
        form = RegisterEmailAddress()

    return render_to_response(register_template_name, {'form': form},
                              context_instance=RequestContext(request))
Example #4
0
    def test_move_cat1_p2_to_cat2(self):
        """
             Test moving post p2 from category cat1 directly into category cat2.

             Expected output is to have new thread (created from post p2) in category cat2.
             Thread cat1_p1 in category c1 will have less posts now
        """
        mv1url = self.cat1_p2.get_absolute_moveposturl()
        self.assertEqual(
            mv1url,
            sph_reverse('move_post_1', kwargs={'post_id': self.cat1_p2.pk}))

        # check first step
        response = self.client.get(mv1url, {})
        self.assertEqual(response.status_code, 200)

        # check second step (category is selected)
        mv2url = sph_reverse('move_post_2',
                             kwargs={
                                 'post_id': self.cat1_p2.pk,
                                 'category_id': self.cat2.pk
                             })
        response = self.client.get(mv2url, {})
        self.assertEqual(response.status_code, 200)

        # check step 3 (with GET) - annotation form for post moved into category
        mv3url = sph_reverse('move_post_3',
                             kwargs={
                                 'post_id': self.cat1_p2.pk,
                                 'category_id': self.cat2.pk
                             })
        response = self.client.get(mv3url, {})
        self.assertEqual(response.status_code, 200)

        # submit annotation form and move the post!
        self.assertEqual(self.cat2.threadCount(), 1)
        response = self.client.post(mv3url, {'body': 'test body'})
        self.assertEqual(response.status_code, 302)

        # get fresh instance of moved post
        p2 = Post.objects.get(pk=self.cat1_p2.pk)

        # check if success message was created
        self.assertEqual(self.superuser.message_set.count(), 1)
        # check if new thread exists in category cat2
        self.assertEqual(self.cat2.threadCount(), 2)
        # check if post p2 was removed form thread p1
        self.assertEqual(self.cat1_p1.postCount(), 2)
        # check if post p2 is now new thread in category cat2
        self.assertEqual(p2.get_thread(), p2)
        # check if ThreadInformation for post p1 was updated
        ti = self.cat1_p1.get_threadinformation()
        self.assertEqual(ti.post_count, 2)
        # check if number of ThreadInformation objects has been changed
        self.assertEqual(ThreadInformation.objects.all().count(), 3)
        # check ThreadInformation for new thread
        ti2 = p2.get_threadinformation()
        self.assertEqual(ti2.post_count, 1)
def catchup(request, group, category_id):
    if category_id == '0':
        ThreadLastVisit.objects.filter(user = request.user).delete() 
        CategoryLastVisit.objects.filter(user = request.user).update(lastvisit = datetime.today(), oldlastvisit = None)
        req = HttpResponseRedirect(sph_reverse('sphboard-index'))
    else:
        category = get_object_or_404(Category, pk = category_id )
        category.catchup(request.session, request.user)
        req = HttpResponseRedirect( sph_reverse('sphene.sphboard.views.showCategory' , kwargs = {'category_id': category_id } ) )

    req.sph_lastmodified = True
    return req
Example #6
0
    def test_move_cat1_p2_to_cat2(self):
        """
             Test moving post p2 from category cat1 directly into category cat2.

             Expected output is to have new thread (created from post p2) in category cat2.
             Thread cat1_p1 in category c1 will have less posts now
        """
        mv1url = self.cat1_p2.get_absolute_moveposturl()
        self.assertEqual(mv1url, sph_reverse('move_post_1', kwargs={'post_id':self.cat1_p2.pk}))

        # check first step
        response = self.client.get(mv1url, {})
        self.assertEqual(response.status_code, 200)

        # check second step (category is selected)
        mv2url = sph_reverse('move_post_2', kwargs={'post_id':self.cat1_p2.pk,
                                                    'category_id':self.cat2.pk})
        response = self.client.get(mv2url, {})
        self.assertEqual(response.status_code, 200)

        # check step 3 (with GET) - annotation form for post moved into category
        mv3url = sph_reverse('move_post_3', kwargs={'post_id':self.cat1_p2.pk,
                                                        'category_id':self.cat2.pk})
        response = self.client.get(mv3url, {})
        self.assertEqual(response.status_code, 200)

        # submit annotation form and move the post!
        self.assertEqual(self.cat2.threadCount(), 1)
        response = self.client.post(mv3url, {'body':'test body'})
        self.assertEqual(response.status_code, 302)

        # get fresh instance of moved post
        p2 = Post.objects.get(pk=self.cat1_p2.pk)

        # check if success message was created
        self.assertEqual(self.superuser.message_set.count(), 1)
        # check if new thread exists in category cat2
        self.assertEqual(self.cat2.threadCount(), 2)
        # check if post p2 was removed form thread p1
        self.assertEqual(self.cat1_p1.postCount(), 2)
        # check if post p2 is now new thread in category cat2
        self.assertEqual(p2.get_thread(), p2)
        # check if ThreadInformation for post p1 was updated
        ti = self.cat1_p1.get_threadinformation()
        self.assertEqual(ti.post_count, 2)
        # check if number of ThreadInformation objects has been changed
        self.assertEqual(ThreadInformation.objects.all().count(), 3)
        # check ThreadInformation for new thread
        ti2 = p2.get_threadinformation()
        self.assertEqual(ti2.post_count, 1)
Example #7
0
def catchup(request, group, category_id):
    if category_id == '0':
        ThreadLastVisit.objects.filter(user=request.user).delete()
        CategoryLastVisit.objects.filter(user=request.user).update(
            lastvisit=timezone.now(), oldlastvisit=None)
        req = HttpResponseRedirect(sph_reverse('sphboard-index'))
    else:
        category = get_object_or_404(Category, pk=category_id)
        category.catchup(request.session, request.user)
        req = HttpResponseRedirect(
            sph_reverse('sphene.sphboard.views.showCategory',
                        kwargs={'category_id': category_id}))

    req.sph_lastmodified = True
    return req
Example #8
0
def admin_post_delete(request, group, user_id, post_id):
    post = get_object_or_404(Post, author=user_id, pk=post_id)
    if not post.allow_hiding():
        raise PermissionDenied()
    post.hide()
    messages.success(request,  message = ugettext(u'Post deleted') )
    return HttpResponseRedirect(sph_reverse('sphboard_admin_user_posts' , kwargs = {'user_id': user_id } ))
Example #9
0
def toggle_monitor(request, group, monitortype, object_id, monitor_user_id=None):
    if not request.user.is_authenticated():
        raise PermissionDenied()
    obj = None
    if monitortype == 'group':
        obj = group
        object_id = 0
    elif monitortype == 'category':
        obj = Category.objects.get( pk = object_id )
    elif monitortype == 'thread':
        obj = Post.objects.get( pk = object_id )

    new_monitor = None
    if monitor_user_id:
        monitor_user = User.objects.get(pk=monitor_user_id)
        new_monitor = obj.toggle_monitor(user=monitor_user)
    else:
        new_monitor = obj.toggle_monitor()

    if new_monitor:
        messages.success(request,  message = ugettext(u'Successfully created email notification monitor.') )
    else:
        messages.success(request,  message = ugettext(u'Removed email notification monitor.') )

    if 'next' in request.GET:
        return HttpResponseRedirect( request.GET['next'] )
    if monitortype == 'group':
        return HttpResponseRedirect(sph_reverse('sphboard-index'))
    return HttpResponseRedirect(obj.get_absolute_url())
    def inner(*args, **kwargs):
        from sphene.community.sphutils import sph_reverse
        # Find urlconf ...
        bits = func(*args, **kwargs)
        viewname, args, kwargs = bits

        return sph_reverse(viewname, args=args, kwargs=kwargs)
Example #11
0
    def save_post(self, newpost, data):
        super(BlogCategoryType, self).save_post(newpost, data)
        if newpost.thread is not None:
            return
        try:
            ext = newpost.blogpostextension_set.get()
        except BlogPostExtension.DoesNotExist:
            ext = BlogPostExtension( post = newpost, )


        ext.slug = data['slug']
        ext.status = data['status']
        ext.save()

        tag_set_labels( newpost, data['tags'] )

        if newpost.is_new_post:
            try:
                config = BlogCategoryConfig.objects.get( \
                    category = self.category)

                if config.enable_googleblogping:
                    # If enabled, ping google blogsearch.
                    import urllib
                    url = self.category.group.get_baseurl()
                    blog_feed_url = sph_reverse('sphblog-feeds', urlconf=get_current_urlconf(), kwargs = { 'category_id': self.category.id })
                    pingurl = 'http://blogsearch.google.com/ping?%s' % \
                        urllib.urlencode( \
                        { 'name': self.category.name,
                          'url': ''.join((url, self.category.get_absolute_url()),),
                          'changesURL': ''.join((url, blog_feed_url),) } )
                    urllib.urlopen( pingurl )

            except BlogCategoryConfig.DoesNotExist:
                pass
Example #12
0
def sph_publicemailaddress(value):
    if get_sph_setting('community_email_anonymous_require_captcha'):
        # as a security constraint we don't return the public email
        # address if the user is not logged in.
        if not get_current_user().is_authenticated():
            validated = get_current_request().session.get(
                'sph_email_captcha_validated', 0)

            # if the timeout is reached or the captcha was never entered
            # provide a link for the user to enter the captcha.
            if validated < time() - get_sph_setting(
                    'community_email_anonymous_require_captcha_timeout'):
                return mark_safe('<a href="%s">%s</a>' %
                                 (sph_reverse('sph_reveal_emailaddress', (), {
                                     'user_id': value.id,
                                 }), ugettext('Reveal this emailaddress')))

    if get_sph_setting('community_email_show_only_public'):
        try:
            return CommunityUserProfile.objects.get(
                user=value, ).public_emailaddress
        except CommunityUserProfile.DoesNotExist:
            pass
        return ''

    try:
        profile = CommunityUserProfile.objects.get(user=value, )
    except CommunityUserProfile.DoesNotExist:
        return "n/a"  #value.email
    return profile.public_emailaddress or value.email
 def get_absolute_url_for_category(self):
     try:
         blog_url = sph_reverse('sphblog_category_index', kwargs = { 'category_id': self.category.id })
         return blog_url
     except Exception, e:
         #print "err.. argl %s" % str(e)
         return None
Example #14
0
def edit_poll(request, group, poll_id):
    poll = get_object_or_404(Poll, pk = poll_id)
    if not poll.allow_editing():
        raise PermissionDenied()

    postdata = None
    if request.method == 'POST':
        postdata = request.POST

    form = PollForm(postdata, instance = poll)
    choiceforms = [ PollChoiceForm( postdata,
                                    prefix = 'choice_%d' % choice.id,
                                    instance = choice,
                                    ) for choice in poll.pollchoice_set.all() ]

    if request.method == 'POST' and form.is_valid() \
            and not [ True for choiceform in choiceforms if not choiceform.is_valid() ]:
        form.save()
        for choiceform in choiceforms:
            choiceform.save()

        return HttpResponseRedirect(sph_reverse('sphene.sphboard.views.showThread',
                                                kwargs = { 'thread_id': poll.post.get_thread().id }))

    return sph_render_to_response('sphene/sphboard/edit_poll.html',
                                  { 'form': form,
                                    'choiceforms': choiceforms,
                                    })
Example #15
0
def profile(request, group, user_id):
    user = get_object_or_404(User, pk = user_id)
    has_edit_permission = False
    profile_edit_url = None

    requester = request.user
    
    if user == requester or \
        (requester and requester.is_authenticated() and requester.is_superuser):
        has_edit_permission = True
        profile_edit_url = sph_reverse( 'sphene.community.views.profile_edit', (), { 'user_id': user.id, })

    ret = profile_display.send(None, request = request,
                               user = user, )

    additionalprofile = ''
    blocks = list()
    for listener in ret:
        if listener[1]:
            response = listener[1]

            if isinstance( response, dict ):
                blocks.append(response['block'])
                response = response['additionalprofile']

            additionalprofile += response
    
    return render_to_response( 'sphene/community/profile.html',
                               { 'profile_user': user,
                                 'profile_blocks': blocks,
                                 'has_edit_permission': has_edit_permission,
                                 'profile_edit_url': profile_edit_url,
                                 'additionalprofile': mark_safe( additionalprofile ),
                                 },
                               context_instance = RequestContext( request ))
Example #16
0
def sph_publicemailaddress(value):
    if get_sph_setting('community_email_anonymous_require_captcha'):
        # as a security constraint we don't return the public email
        # address if the user is not logged in.
        if not get_current_user().is_authenticated:
            validated = get_current_request().session.get('sph_email_captcha_validated', 0)

            # if the timeout is reached or the captcha was never entered
            # provide a link for the user to enter the captcha.
            if validated < time() - get_sph_setting('community_email_anonymous_require_captcha_timeout'):
                return mark_safe('<a href="%s">%s</a>' % (
                sph_reverse('sph_reveal_emailaddress', kwargs={'user_id': value.id, }), _('Reveal this emailaddress')))

    if get_sph_setting('community_email_show_only_public'):
        try:
            return CommunityUserProfile.objects.get(user=value, ).public_emailaddress
        except CommunityUserProfile.DoesNotExist:
            pass
        return ''

    try:
        profile = CommunityUserProfile.objects.get(user=value, )
    except CommunityUserProfile.DoesNotExist:
        return "n/a"  # value.email
    return profile.public_emailaddress or value.email
Example #17
0
def edit_poll(request, group, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    if not poll.allow_editing():
        raise PermissionDenied()

    postdata = None
    if request.method == 'POST':
        postdata = request.POST

    form = PollForm(postdata, instance=poll)
    choiceforms = [
        PollChoiceForm(
            postdata,
            prefix='choice_%d' % choice.id,
            instance=choice,
        ) for choice in poll.pollchoice_set.all()
    ]

    if request.method == 'POST' and form.is_valid() \
            and not [ True for choiceform in choiceforms if not choiceform.is_valid() ]:
        form.save()
        for choiceform in choiceforms:
            choiceform.save()

        return HttpResponseRedirect(
            sph_reverse('sphene.sphboard.views.showThread',
                        kwargs={'thread_id': poll.post.get_thread().id}))

    return sph_render_to_response('sphene/sphboard/edit_poll.html', {
        'form': form,
        'choiceforms': choiceforms,
    })
def edit_poll(request, group, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    if not poll.allow_editing():
        raise PermissionDenied()

    postdata = None
    if request.method == "POST":
        postdata = request.POST

    form = PollForm(postdata, instance=poll)
    choiceforms = [
        PollChoiceForm(postdata, prefix="choice_%d" % choice.id, instance=choice)
        for choice in poll.pollchoice_set.all()
    ]

    if (
        request.method == "POST"
        and form.is_valid()
        and not [True for choiceform in choiceforms if not choiceform.is_valid()]
    ):
        form.save()
        for choiceform in choiceforms:
            choiceform.save()

        return HttpResponseRedirect(
            sph_reverse("sphene.sphboard.views.showThread", kwargs={"thread_id": poll.post.get_thread().id})
        )

    return sph_render_to_response("sphene/sphboard/edit_poll.html", {"form": form, "choiceforms": choiceforms})
Example #19
0
    def inner(*args, **kwargs):
        from sphene.community.sphutils import sph_reverse
        # Find urlconf ...
        bits = func(*args, **kwargs)
        viewname, args, kwargs = bits

        return sph_reverse(viewname, args=args, kwargs=kwargs)
Example #20
0
    def render(self, context):
        from django.urls import reverse, NoReverseMatch
        args = [arg.resolve(context) for arg in self.args]
        kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()}
        view_name = self.view_name.resolve(context)
        if view_name == '':
            log.error('Error while resolving sph_url2 for %r / %s', self.view_name, self.view_name)
            return ''

        try:
            current_app = context.request.current_app
        except AttributeError:
            try:
                current_app = context.request.resolver_match.namespace
            except AttributeError:
                current_app = None
        # Try to look up the URL. If it fails, raise NoReverseMatch unless the
        # {% url ... as var %} construct is used, in which case return nothing.
        url = ''
        try:
            url = sph_reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
        except NoReverseMatch:
            if self.asvar is None:
                raise

        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            if context.autoescape:
                url = conditional_escape(url)
            return url
Example #21
0
    def test_move_cat1_p1_to_cat2_p1(self):
        """
             Test moving post cat1_p1 (root post of thread!) from thread cat1_p1 into thread cat2_p1.

             Expected output is to have thread cat2_p1 updated and containing 2 posts.
             Thread cat1_p1 should be updated too as it now contains only 2 posts
        """
        mv3url = sph_reverse('move_post_3', kwargs={'post_id':self.cat1_p1.pk,
                                                    'category_id':self.cat1.pk,
                                                    'thread_id':self.cat2_p1.pk})
        # submit annotation form and move the post!
        self.assertEqual(self.cat1.threadCount(), 1)
        response = self.client.post(mv3url, {'body':'test body'})
        self.assertEqual(response.status_code, 302)

        # get fresh instances of posts
        cat1_p1 = Post.objects.get(pk=self.cat1_p1.pk)
        cat1_p2 = Post.objects.get(pk=self.cat1_p2.pk)
        cat2_p1 = Post.objects.get(pk=self.cat2_p1.pk)

        # check if success message was created
        self.assertEqual(self.superuser.message_set.count(), 1)
        # check if thread cat2_p1 was updated
        ti = cat2_p1.get_threadinformation()
        self.assertEqual(ti.post_count, 2)
        # check if ThreadInformation for post p2 was created properly
        ti = cat1_p2.get_threadinformation()
        self.assertEqual(ti.post_count, 2)
        self.assertEqual(ti.category, self.cat1)
        # check if post cat1_p1 is now in thread cat2_p1
        self.assertEqual(cat1_p1.get_thread(), cat2_p1)
        # check if post cat1_p1 was added at the end of thread
        self.assertEqual(cat2_p1.get_latest_post(), cat1_p1)
Example #22
0
    def test_move_cat2_p1_to_cat1(self):
        """
             Test moving post p1 from category cat2 directly into category cat1.

             Expected output is to have new thread (created from post cat2_p1) in category c1.
             Old ThreadInformation object from cat2 should be removed.
        """
        mv3url = sph_reverse('move_post_3', kwargs={'post_id':self.cat2_p1.pk,
                                                    'category_id':self.cat1.pk})
        # submit annotation form and move the post!
        self.assertEqual(self.cat1.threadCount(), 1)
        response = self.client.post(mv3url, {'body':'test body'})
        self.assertEqual(response.status_code, 302)

        # get fresh instances of posts
        cat2_p1 = Post.objects.get(pk=self.cat2_p1.pk)

        # check if success message was created
        self.assertEqual(self.superuser.message_set.count(), 1)
        # check if new thread exists in cat1
        self.assertEqual(self.cat1.threadCount(), 2)
        # check if no threads left in cat2
        self.assertEqual(self.cat2.threadCount(), 0)
        # check if post cat2_p1 is thread
        self.assertEqual(cat2_p1.get_thread(), cat2_p1)
        # check if ThreadInformation for post cat2_p1 was created properly
        ti = cat2_p1.get_threadinformation()
        self.assertEqual(ti.post_count, 1)
        self.assertEqual(ti.category, self.cat1)
Example #23
0
    def test_move_cat1_p1_to_cat2(self):
        """
             Test moving post p1 (root post of thread!) from category cat1 directly
             into category cat2.

             Expected output is to have new thread (created from post p1) in category cat2
             and new thread in category cat1 created from second post in former p1 thread.
             Old ThreadInformation object for thread p1 should be removed.
             Two new ThreadInformation objects will be crated
        """
        mv3url = sph_reverse('move_post_3', kwargs={'post_id':self.cat1_p1.pk,
                                                    'category_id':self.cat2.pk})
        # submit annotation form and move the post!
        self.assertEqual(self.cat2.threadCount(), 1)
        response = self.client.post(mv3url, {'body':'test body'})
        self.assertEqual(response.status_code, 302)

        # get fresh instances of posts
        p1 = Post.objects.get(pk=self.cat1_p1.pk)
        p2 = Post.objects.get(pk=self.cat1_p2.pk)

        # check if success message was created
        self.assertEqual(self.superuser.message_set.count(), 1)
        # check if new thread exists in category cat2
        self.assertEqual(self.cat2.threadCount(), 2)
        # check if post p2 is now thread
        
        self.assertEqual(p2.get_thread(), p2)
        # check if post p1 is now new thread in category cat2
        self.assertEqual(p1.get_thread(), p1)
        # check if ThreadInformation for post p2 was created properly
        ti = p2.get_threadinformation()
        self.assertEqual(ti.post_count, 2)
        # check if number of ThreadInformation objects has been changed
        self.assertEqual(ThreadInformation.objects.all().count(), 3)
Example #24
0
    def test_move_cat2_p1_to_cat1(self):
        """
             Test moving post p1 from category cat2 directly into category cat1.

             Expected output is to have new thread (created from post cat2_p1) in category c1.
             Old ThreadInformation object from cat2 should be removed.
        """
        mv3url = sph_reverse('move_post_3',
                             kwargs={
                                 'post_id': self.cat2_p1.pk,
                                 'category_id': self.cat1.pk
                             })
        # submit annotation form and move the post!
        self.assertEqual(self.cat1.threadCount(), 1)
        response = self.client.post(mv3url, {'body': 'test body'})
        self.assertEqual(response.status_code, 302)

        # get fresh instances of posts
        cat2_p1 = Post.objects.get(pk=self.cat2_p1.pk)

        # check if success message was created
        self.assertEqual(self.superuser.message_set.count(), 1)
        # check if new thread exists in cat1
        self.assertEqual(self.cat1.threadCount(), 2)
        # check if no threads left in cat2
        self.assertEqual(self.cat2.threadCount(), 0)
        # check if post cat2_p1 is thread
        self.assertEqual(cat2_p1.get_thread(), cat2_p1)
        # check if ThreadInformation for post cat2_p1 was created properly
        ti = cat2_p1.get_threadinformation()
        self.assertEqual(ti.post_count, 1)
        self.assertEqual(ti.category, self.cat1)
Example #25
0
    def test_move_cat1_p3_to_cat2_p1(self):
        """
             Test moving post p3 from thread cat1_p1 into thread cat2_p1.

             Expected output is to have thread cat2_p1 updated and containing 2 posts.
             Thread cat1_p1 should be updated too as it now contains only 2 posts
        """
        mv3url = sph_reverse('move_post_3',
                             kwargs={
                                 'post_id': self.cat1_p3.pk,
                                 'category_id': self.cat1.pk,
                                 'thread_id': self.cat2_p1.pk
                             })
        # submit annotation form and move the post!
        self.assertEqual(self.cat1.threadCount(), 1)
        response = self.client.post(mv3url, {'body': 'test body'})
        self.assertEqual(response.status_code, 302)

        # get fresh instances of posts
        p1 = Post.objects.get(pk=self.cat1_p1.pk)
        p3 = Post.objects.get(pk=self.cat1_p3.pk)
        cat2_p1 = Post.objects.get(pk=self.cat2_p1.pk)

        # check if success message was created
        self.assertEqual(self.superuser.message_set.count(), 1)
        # check if thread cat2_p1 was updated
        ti = cat2_p1.get_threadinformation()
        self.assertEqual(ti.post_count, 2)
        # check if ThreadInformation for post p1 was updated properly
        ti = p1.get_threadinformation()
        self.assertEqual(ti.post_count, 2)
        self.assertEqual(ti.category, self.cat1)
        # check if post cat1_p3 is now in thread cat2_p1
        self.assertEqual(p3.get_thread(), cat2_p1)
Example #26
0
def sph_url(view):
    req = get_current_request()
    urlconf = getattr(req, 'urlconf', None)
    try:
        return sph_reverse(view)
    except:
        log.exception('Unable to reverse sph_url for view %r' % view)
        return 'NOT FOUND'
Example #27
0
def sph_url(view):
    req = get_current_request()
    urlconf = getattr(req, 'urlconf', None)
    try:
        return sph_reverse(view)
    except:
        log.exception('Unable to reverse sph_url for view %r' % view)
        return 'NOT FOUND'
Example #28
0
def admin_post_delete(request, group, user_id, post_id):
    post = get_object_or_404(Post, author=user_id, pk=post_id)
    if not post.allow_hiding():
        raise PermissionDenied()
    post.hide()
    messages.success(request, message=ugettext(u'Post deleted'))
    return HttpResponseRedirect(
        sph_reverse('sphboard_admin_user_posts', kwargs={'user_id': user_id}))
Example #29
0
def register(request, group = None, frm = None, register_template_name = 'sphene/community/register.html', email_sent_template_name = 'sphene/community/register_emailsent.html'):

    if request.method == 'POST':
        form = RegisterEmailAddress(request.POST)
        if form.is_valid():
            regdata = form.cleaned_data
            email_address = regdata['email_address']
            if not group:
                subject = _(u'Email verification required')
            else:
                subject = _(u'Email verification required for site %(site_name)s') % {'site_name': group.get_name()}
            validationcode = cryptString( settings.SECRET_KEY, email_address )
	    if frm:
		mail_context_path = sph_reverse( 'sphene.community.views.register_hash', (), { 'emailHash': validationcode, } ).split('community')[1]
	    else:
		mail_context_path = sph_reverse( 'sphene.community.views.register_hash', (), { 'emailHash': validationcode, } )
	    
            mail_context = RequestContext(request,
                                          {
                    'email': email_address,
                    'baseurl': group.baseurl,
                    'path': mail_context_path,
                    'validationcode': validationcode,
                    'group': group,
                    })
            text_part = loader.get_template('sphene/community/accounts/account_verification_email.txt') \
                .render(mail_context)
            html_part = loader.get_template('sphene/community/accounts/account_verification_email.html') \
                .render(mail_context)

            msg = EmailMultiAlternatives(subject, text_part, None, [email_address])
            msg.attach_alternative(html_part, "text/html")
            msg.send()

            return render_to_response( email_sent_template_name,
                                       { 'email': email_address,
                                         },
                                       context_instance = RequestContext(request) )
        pass
    else:
        form = RegisterEmailAddress()

    return render_to_response( register_template_name,
                               { 'form': form },
                               context_instance = RequestContext(request) )
 def get_absolute_url_for_category(self):
     try:
         blog_url = sph_reverse(
             'sphblog_category_index_slug',
             kwargs={'category_slug': self.category.slug})
         return blog_url
     except Exception as e:
         #print "err.. argl %s" % str(e)
         return None
Example #31
0
def register(request, group=None):
    if request.method == 'POST':
        form = RegisterEmailAddress(request.POST)
        if form.is_valid():
            regdata = form.cleaned_data
            email_address = regdata['email_address']
            mail_domain = email_address.split('@')[1]
            logger.info('ip: %s, email: %s' %
                        (get_client_ip(request), email_address))
            # do not tell spammers that we have not sent email :)
            if mail_domain not in getattr(settings,
                                          'BLACKLISTED_EMAIL_DOMAINS', []):
                if not group:
                    subject = ugettext(u'Email verification required')
                else:
                    subject = ugettext(
                        u'Email verification required for site %(site_name)s'
                    ) % {
                        'site_name': group.get_name()
                    }
                validationcode = md5(
                    (settings.SECRET_KEY +
                     email_address).encode('utf-8')).hexdigest()
                mail_context = {
                    'email':
                    email_address,
                    'baseurl':
                    group.baseurl,
                    'path':
                    sph_reverse('sph_register_hash',
                                kwargs={
                                    "email": quote(email_address),
                                    'emailHash': validationcode,
                                }),
                    'validationcode':
                    validationcode,
                    'group':
                    group,
                }
                text_part = loader.get_template('sphene/community/accounts/account_verification_email.txt') \
                    .render(mail_context, request=request)
                html_part = loader.get_template('sphene/community/accounts/account_verification_email.html') \
                    .render(mail_context, request=request)

                msg = EmailMultiAlternatives(subject, text_part, None,
                                             [email_address])
                msg.attach_alternative(html_part, "text/html")
                msg.send()

            return render(request, 'sphene/community/register_emailsent.html',
                          {'email': email_address})
        pass
    else:
        form = RegisterEmailAddress()

    return render(request, 'sphene/community/register.html', {'form': form})
Example #32
0
def admin_permission_rolegroup_list(request, group):
    if request.method == 'POST':
        name = request.POST['name']
        if name:
            RoleGroup(group = group,
                      name = name).save()
            return HttpResponseRedirect(sph_reverse('community_admin_permission_rolegroup_list'))
    rolegroups = RoleGroup.objects.filter( group = group )
    return render_to_response( 'sphene/community/admin/permission/rolegroup_list.html',
                               { 'rolegroups': rolegroups, },
                               context_instance = RequestContext(request) )
Example #33
0
def admin_posts_delete(request, group, user_id):
    posts = Post.objects.filter(author=user_id)
    if posts:
        if not posts[0].allow_hiding():
            raise PermissionDenied()
        for post in posts:
            post.hide()
        messages.success(request,  message = ugettext(u'All posts deleted') )
    else:
        messages.success(request,  message = ugettext(u'No posts to delete') )
    return HttpResponseRedirect(sph_reverse('sphboard_admin_user_posts' , kwargs = {'user_id': user_id } ))
Example #34
0
def admin_posts_delete(request, group, user_id):
    posts = Post.objects.filter(author=user_id)
    if posts:
        if not posts[0].allow_hiding():
            raise PermissionDenied()
        for post in posts:
            post.hide()
        messages.success(request, message=ugettext(u'All posts deleted'))
    else:
        messages.success(request, message=ugettext(u'No posts to delete'))
    return HttpResponseRedirect(
        sph_reverse('sphboard_admin_user_posts', kwargs={'user_id': user_id}))
Example #35
0
def blogindex(request,
              group,
              category_id=None,
              category_slug=None,
              page=1,
              year=None,
              month=None):
    """
    shows a blog posts list. year and month parameters
    are used for archive functionality.
    """

    category_info = get_category_info(category_id=category_id,
                                      category_slug=category_slug,
                                      group=group)
    if not category_info:
        return render_to_response('sphene/sphblog/nocategory.html', {},
                                  context_instance=RequestContext(request))
    context_variables = {}
    if year:
        context_variables['archive_year'] = year
        year = int(year)

        if month:
            context_variables['archive_month'] = month
            month = int(month)

    threads = get_posts_queryset(group, category_info[0], year, month)

    paged_threads = get_paged_objects(threads, page)

    allowpostcategories = filter(Category.has_post_thread_permission,
                                 category_info[0])
    #blog_feed_url = reverse('sphblog-feeds', urlconf=get_current_urlconf(), args = ('latestposts',), kwargs = { 'groupName': group.name })
    blog_feed_url = sph_reverse('sphblog-feeds')
    #, kwargs = { 'url': 'latestposts' })
    add_rss_feed(blog_feed_url, 'Blog RSS Feed')
    all_tags = get_tags_for_categories(category_info[0])

    context_variables.update({
        'allowpostcategories': allowpostcategories,
        'threads': paged_threads,
        'blog_feed_url': blog_feed_url,
        'all_tags': all_tags,
        'category': category_info[1],
        'categories': category_info[0],
        'group': group,
    })

    return render_to_response('sphene/sphblog/blogindex.html',
                              context_variables,
                              context_instance=RequestContext(request))
Example #36
0
def admin_permission_rolegroup_list(request, group):
    if request.method == 'POST':
        name = request.POST['name']
        if name:
            RoleGroup(group=group, name=name).save()
            return HttpResponseRedirect(
                sph_reverse('community_admin_permission_rolegroup_list'))
    rolegroups = RoleGroup.objects.filter(group=group)
    return render_to_response(
        'sphene/community/admin/permission/rolegroup_list.html', {
            'rolegroups': rolegroups,
        },
        context_instance=RequestContext(request))
Example #37
0
def admin_permission_rolegroup_list(request, group):
    if not has_permission_flag(request.user, 'community_manage_roles'):
        raise PermissionDenied()
    if request.method == 'POST':
        name = request.POST['name']
        if name:
            RoleGroup(group=group, name=name).save()
            return HttpResponseRedirect(
                sph_reverse('community_admin_permission_rolegroup_list'))
    rolegroups = RoleGroup.objects.filter(group=group)
    return render(request,
                  'sphene/community/admin/permission/rolegroup_list.html',
                  {'rolegroups': rolegroups})
Example #38
0
def admin_permission_rolegroup_list(request, group):
    if not has_permission_flag(request.user, 'community_manage_roles'):
        raise PermissionDenied()
    if request.method == 'POST':
        name = request.POST['name']
        if name:
            RoleGroup(group=group,
                      name=name).save()
            return HttpResponseRedirect(sph_reverse('community_admin_permission_rolegroup_list'))
    rolegroups = RoleGroup.objects.filter(group=group)
    return render(
        request,
        'sphene/community/admin/permission/rolegroup_list.html',
        {'rolegroups': rolegroups}
    )
Example #39
0
def register(request, group=None):
    if request.method == 'POST':
        form = RegisterEmailAddress(request.POST)
        if form.is_valid():
            regdata = form.cleaned_data
            email_address = regdata['email_address']
            mail_domain = email_address.split('@')[1]
            logger.info('ip: %s, email: %s' % (get_client_ip(request), email_address))
            # do not tell spammers that we have not sent email :)
            if mail_domain not in getattr(settings, 'BLACKLISTED_EMAIL_DOMAINS', []):
                if not group:
                    subject = ugettext(u'Email verification required')
                else:
                    subject = ugettext(u'Email verification required for site %(site_name)s') % {
                        'site_name': group.get_name()}
                validationcode = md5(
                    (settings.SECRET_KEY + email_address).encode('utf-8')).hexdigest()
                mail_context = {
                    'email': email_address,
                    'baseurl': group.baseurl,
                    'path': sph_reverse('sph_register_hash',
                                        kwargs={"email": quote(email_address), 'emailHash': validationcode, }),
                    'validationcode': validationcode,
                    'group': group,
                }
                text_part = loader.get_template('sphene/community/accounts/account_verification_email.txt') \
                    .render(mail_context, request=request)
                html_part = loader.get_template('sphene/community/accounts/account_verification_email.html') \
                    .render(mail_context, request=request)

                msg = EmailMultiAlternatives(subject, text_part, None, [email_address])
                msg.attach_alternative(html_part, "text/html")
                msg.send()

            return render(
                request,
                'sphene/community/register_emailsent.html',
                {'email': email_address})
        pass
    else:
        form = RegisterEmailAddress()

    return render(
        request,
        'sphene/community/register.html',
        {'form': form}
    )
Example #40
0
def profile(request,
            group,
            user_id,
            profile_template_name='sphene/community/profile.html',
            frm=None):
    user = get_object_or_404(User, pk=user_id)
    has_edit_permission = False
    profile_edit_url = None

    if user == request.user:
        has_edit_permission = True
        if frm:

            profile_edit_url = '/accounts/profile/edit/%d/' % (user.id, )
        else:
            profile_edit_url = sph_reverse(
                'sphene.community.views.profile_edit', (), {
                    'user_id': user.id,
                })

    ret = profile_display.send(
        None,
        request=request,
        user=user,
    )

    additionalprofile = ''
    blocks = list()
    for listener in ret:
        if listener[1]:
            response = listener[1]

            if isinstance(response, dict):
                blocks.append(response['block'])
                response = response['additionalprofile']

            additionalprofile += response

    return render_to_response(
        profile_template_name, {
            'profile_user': user,
            'profile_blocks': blocks,
            'has_edit_permission': has_edit_permission,
            'profile_edit_url': profile_edit_url,
            'additionalprofile': mark_safe(additionalprofile),
        },
        context_instance=RequestContext(request))
Example #41
0
def profile(request, group, user_id):
    user = get_object_or_404(User, pk=user_id)
    if not request.user.is_superuser:
        if not user.is_active:
            raise Http404
    has_edit_permission = False
    profile_edit_url = None

    requester = request.user

    if user == requester or \
            (requester and requester.is_authenticated and requester.is_superuser):
        has_edit_permission = True
        profile_edit_url = sph_reverse('sph-profile-edit',
                                       args=(),
                                       kwargs={
                                           'user_id': user.id,
                                       })

    ret = profile_display.send(
        None,
        request=request,
        user=user,
    )

    additionalprofile = ''
    blocks = list()
    for listener in ret:
        if listener[1]:
            response = listener[1]

            if isinstance(response, dict):
                blocks.append(response['block'])
                response = response['additionalprofile']

            additionalprofile += response

    return render(
        request, 'sphene/community/profile.html', {
            'profile_user': user,
            'profile_blocks': blocks,
            'has_edit_permission': has_edit_permission,
            'profile_edit_url': profile_edit_url,
            'additionalprofile': mark_safe(additionalprofile),
        })
Example #42
0
def blogindex(request, group, category_id = None, category_slug = None, page = 1, year=None, month=None):
    """
    shows a blog posts list. year and month parameters
    are used for archive functionality.
    """

    category_info = get_category_info(category_id = category_id,
                                      category_slug = category_slug,
                                      group = group)
    if not category_info:
        return render_to_response('sphene/sphblog/nocategory.html',
                                  {},
                                  context_instance = RequestContext(request))
    context_variables = {}
    if year:
        context_variables['archive_year'] = year
        year = int(year)

        if month:
            context_variables['archive_month'] = month
            month = int(month)

    threads = get_posts_queryset(group, category_info[0], year, month)

    paged_threads = get_paged_objects(threads, page)

    allowpostcategories = filter(Category.has_post_thread_permission, category_info[0])
    #blog_feed_url = reverse('sphblog-feeds', urlconf=get_current_urlconf(), args = ('latestposts',), kwargs = { 'groupName': group.name })
    blog_feed_url = sph_reverse('sphblog-feeds');#, kwargs = { 'url': 'latestposts' })
    add_rss_feed( blog_feed_url, 'Blog RSS Feed' )
    all_tags = get_tags_for_categories( category_info[0] )

    context_variables.update({'allowpostcategories': allowpostcategories,
                              'threads': paged_threads,
                              'blog_feed_url': blog_feed_url,
                              'all_tags': all_tags,
                              'category': category_info[1],
                              'categories': category_info[0],
                              'group': group,
                              })

    return render_to_response( 'sphene/sphblog/blogindex.html',
                               context_variables,
                               context_instance = RequestContext(request) )
Example #43
0
    def test_move_cat1_p1_to_cat1(self):
        """
             Test moving post p1 (root post of thread!) from category c1 directly
             into category cat1.

             Expected output is to have new thread (created from post p1) in category c1
             and new thread in category c1 created from second post in former p1 thread.
             Old ThreadInformation object for thread p1 should be removed.
             Two new ThreadInformation objects will be crated
        """
        mv3url = sph_reverse('move_post_3',
                             kwargs={
                                 'post_id': self.cat1_p1.pk,
                                 'category_id': self.cat1.pk
                             })
        # submit annotation form and move the post!
        self.assertEqual(self.cat1.threadCount(), 1)
        response = self.client.post(mv3url, {'body': 'test body'})
        self.assertEqual(response.status_code, 302)

        # get fresh instances of posts
        p1 = Post.objects.get(pk=self.cat1_p1.pk)
        p2 = Post.objects.get(pk=self.cat1_p2.pk)

        # check if success message was created
        self.assertEqual(self.superuser.message_set.count(), 1)
        # check if new thread exists in category cat1
        self.assertEqual(self.cat1.threadCount(), 2)
        # check if post p2 is now thread
        self.assertEqual(p2.get_thread(), p2)
        # check if post p1 is now new thread in category cat1
        self.assertEqual(p1.get_thread(), p1)
        # check if ThreadInformation for post p2 was created properly
        ti = p2.get_threadinformation()
        self.assertEqual(ti.post_count, 2)
        self.assertEqual(ti.category, self.cat1)
        # check if ThreadInformation for post p1 was updated properly
        ti2 = p1.get_threadinformation()
        self.assertEqual(ti2.post_count, 1)
        self.assertEqual(ti2.category, self.cat1)
        # check if number of ThreadInformation objects has been changed
        self.assertEqual(ThreadInformation.objects.all().count(), 3)
Example #44
0
def profile(request, group, user_id):
    user = get_object_or_404(User, pk=user_id)
    has_edit_permission = False
    profile_edit_url = None

    requester = request.user

    if user == requester or \
        (requester and requester.is_authenticated() and requester.is_superuser):
        has_edit_permission = True
        profile_edit_url = sph_reverse('sphene.community.views.profile_edit',
                                       (), {
                                           'user_id': user.id,
                                       })

    ret = profile_display.send(
        None,
        request=request,
        user=user,
    )

    additionalprofile = ''
    blocks = list()
    for listener in ret:
        if listener[1]:
            response = listener[1]

            if isinstance(response, dict):
                blocks.append(response['block'])
                response = response['additionalprofile']

            additionalprofile += response

    return render_to_response(
        'sphene/community/profile.html', {
            'profile_user': user,
            'profile_blocks': blocks,
            'has_edit_permission': has_edit_permission,
            'profile_edit_url': profile_edit_url,
            'additionalprofile': mark_safe(additionalprofile),
        },
        context_instance=RequestContext(request))
Example #45
0
def profile(request, group, user_id):
    user = get_object_or_404(User, pk=user_id)
    if not request.user.is_superuser:
        if not user.is_active:
            raise Http404
    has_edit_permission = False
    profile_edit_url = None

    requester = request.user

    if user == requester or \
            (requester and requester.is_authenticated and requester.is_superuser):
        has_edit_permission = True
        profile_edit_url = sph_reverse('sph-profile-edit', args=(), kwargs={'user_id': user.id, })

    ret = profile_display.send(None, request=request,
                               user=user, )

    additionalprofile = ''
    blocks = list()
    for listener in ret:
        if listener[1]:
            response = listener[1]

            if isinstance(response, dict):
                blocks.append(response['block'])
                response = response['additionalprofile']

            additionalprofile += response

    return render(
        request,
        'sphene/community/profile.html',
        {'profile_user': user,
         'profile_blocks': blocks,
         'has_edit_permission': has_edit_permission,
         'profile_edit_url': profile_edit_url,
         'additionalprofile': mark_safe(additionalprofile),
         }
    )
def toggle_monitor(request, group, monitortype, object_id):
    if not request.user.is_authenticated():
        raise PermissionDenied()
    obj = None
    if monitortype == "group":
        obj = group
        object_id = 0
    elif monitortype == "category":
        obj = Category.objects.get(pk=object_id)
    elif monitortype == "thread":
        obj = Post.objects.get(pk=object_id)

    if obj.toggle_monitor():
        request.user.message_set.create(message=ugettext(u"Successfully created email notification monitor."))
    else:
        request.user.message_set.create(message=ugettext(u"Removed email notification monitor."))

    if "next" in request.GET:
        return HttpResponseRedirect(request.GET["next"])
    if monitortype == "group":
        return HttpResponseRedirect(sph_reverse("sphboard-index"))
    return HttpResponseRedirect(obj.get_absolute_url())
Example #47
0
    def render(self, name, value, attrs=None):
        if not attrs: attrs = {}
        if isinstance(value, list):
            value = ', '.join([tag_label.label for tag_label in value])

        js = ''
        if self.content_type_id is not None:
            attrs['onfocus'] = "%s_init(this);" % (name)
            attrs['autocomplete'] = 'off'
            js = """
<link rel="stylesheet" href="%(media_url)ssphene/community/jqac.css" />
<script language="JavaScript">
<!--
  function %(name)s_get_autocomplete(string, callback) {
    $.get("%(url)s", { content_type_id: "%(content_type_id)d", string: encodeURIComponent(string) },
        function(data) {
          var r=[];
          $(data).find('taglabel').each(function(){
            r.push( { id: $(this).find('id').text(),
                      value: $(this).find('label').text(), } );
          });
          callback( r );
        });
  }
  function %(name)s_init(input) {
    //alert( "content_type_id: %(content_type_id)d" );
    $(input).autocomplete({ ajax_get:%(name)s_get_autocomplete, minchars:1, multi:true });
  }
//-->
</script>""" % {
                'name': name,
                'media_url': settings.MEDIA_URL,
                'content_type_id': self.content_type_id,
                'url': sph_reverse('sph_tags_json_autocompletion', (), {}),
            }

        widget = super(TagWidget, self).render(name, value, attrs)
        return "%s%s" % (js, widget)
Example #48
0
def toggle_monitor(request,
                   group,
                   monitortype,
                   object_id,
                   monitor_user_id=None):
    if not request.user.is_authenticated():
        raise PermissionDenied()
    obj = None
    if monitortype == 'group':
        obj = group
        object_id = 0
    elif monitortype == 'category':
        obj = Category.objects.get(pk=object_id)
    elif monitortype == 'thread':
        obj = Post.objects.get(pk=object_id)

    new_monitor = None
    if monitor_user_id:
        monitor_user = User.objects.get(pk=monitor_user_id)
        new_monitor = obj.toggle_monitor(user=monitor_user)
    else:
        new_monitor = obj.toggle_monitor()

    if new_monitor:
        messages.success(
            request,
            message=ugettext(
                u'Successfully created email notification monitor.'))
    else:
        messages.success(
            request, message=ugettext(u'Removed email notification monitor.'))

    if 'next' in request.GET:
        return HttpResponseRedirect(request.GET['next'])
    if monitortype == 'group':
        return HttpResponseRedirect(sph_reverse('sphboard-index'))
    return HttpResponseRedirect(obj.get_absolute_url())
    def save_post(self, newpost, data):
        super(BlogCategoryType, self).save_post(newpost, data)
        if newpost.thread is not None:
            return
        try:
            ext = newpost.blogpostextension_set.get()
        except BlogPostExtension.DoesNotExist:
            ext = BlogPostExtension(post=newpost, )

        ext.slug = data['slug']
        ext.status = data['status']
        ext.save()

        tag_set_labels(newpost, data['tags'])

        if newpost.is_new_post:
            try:
                config = BlogCategoryConfig.objects.get( \
                    category = self.category)

                if config.enable_googleblogping:
                    # If enabled, ping google blogsearch.
                    import urllib
                    url = self.category.group.get_baseurl()
                    blog_feed_url = sph_reverse(
                        'sphblog-feeds',
                        urlconf=get_current_urlconf(),
                        kwargs={'category_id': self.category.id})
                    pingurl = 'http://blogsearch.google.com/ping?%s' % \
                        urllib.urlencode( \
                        { 'name': self.category.name,
                          'url': ''.join((url, self.category.get_absolute_url()),),
                          'changesURL': ''.join((url, blog_feed_url),) } )
                    urllib.urlopen(pingurl)

            except BlogCategoryConfig.DoesNotExist:
                pass
Example #50
0
def profile(request, group, user_id, profile_template_name = 'sphene/community/profile.html', frm = None):
    user = get_object_or_404(User, pk = user_id)
    has_edit_permission = False
    profile_edit_url = None

    if user == request.user:
        has_edit_permission = True
	if frm:
		
		profile_edit_url = '/accounts/profile/edit/%d/'%(user.id,)
	else:
        	profile_edit_url = sph_reverse( 'sphene.community.views.profile_edit', (), { 'user_id': user.id, })

    ret = profile_display.send(None, request = request,
                               user = user, )

    additionalprofile = ''
    blocks = list()
    for listener in ret:
        if listener[1]:
            response = listener[1]

            if isinstance( response, dict ):
                blocks.append(response['block'])
                response = response['additionalprofile']

            additionalprofile += response
    
    return render_to_response( profile_template_name,
                               { 'profile_user': user,
                                 'profile_blocks': blocks,
                                 'has_edit_permission': has_edit_permission,
                                 'profile_edit_url': profile_edit_url,
                                 'additionalprofile': mark_safe( additionalprofile ),
                                 },
                               context_instance = RequestContext( request ))
Example #51
0
    def render(self, name, value, attrs=None):
        if not attrs: attrs = { }
        if isinstance(value, list):
            value = ', '.join([ tag_label.label for tag_label in value ])

        js = ''
        if self.content_type_id is not None:
            attrs['onfocus'] = "%s_init(this);" % ( name )
            attrs['autocomplete'] = 'off'
            js = """
<link rel="stylesheet" href="%(media_url)ssphene/community/jqac.css" />
<script language="JavaScript">
<!--
  function %(name)s_get_autocomplete(string, callback) {
    $.get("%(url)s", { content_type_id: "%(content_type_id)d", string: encodeURIComponent(string) },
        function(data) {
          var r=[];
          $(data).find('taglabel').each(function(){
            r.push( { id: $(this).find('id').text(),
                      value: $(this).find('label').text() } );
          });
          callback( r );
        });
  }
  function %(name)s_init(input) {
    //alert( "content_type_id: %(content_type_id)d" );
    $(input).autocomplete({ ajax_get:%(name)s_get_autocomplete, minchars:1, multi:true });
  }
//-->
</script>""" % { 'name': name, 
                 'media_url': settings.STATIC_URL, 
                 'content_type_id': self.content_type_id,
                 'url': sph_reverse( 'sph_tags_json_autocompletion', (), {} ), };

        widget = super(TagWidget, self).render(name, value, attrs)
        return "%s%s" % (js, widget)
Example #52
0
    def render(self, context):
        from django.urls import reverse, NoReverseMatch
        args = [arg.resolve(context) for arg in self.args]
        kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()}
        view_name = self.view_name.resolve(context)
        if view_name == '':
            log.error('Error while resolving sph_url2 for %r / %s',
                      self.view_name, self.view_name)
            return ''

        try:
            current_app = context.request.current_app
        except AttributeError:
            try:
                current_app = context.request.resolver_match.namespace
            except AttributeError:
                current_app = None
        # Try to look up the URL. If it fails, raise NoReverseMatch unless the
        # {% url ... as var %} construct is used, in which case return nothing.
        url = ''
        try:
            url = sph_reverse(view_name,
                              args=args,
                              kwargs=kwargs,
                              current_app=current_app)
        except NoReverseMatch:
            if self.asvar is None:
                raise

        if self.asvar:
            context[self.asvar] = url
            return ''
        else:
            if context.autoescape:
                url = conditional_escape(url)
            return url
Example #53
0
def showCategory(request, group = None, category_id = None, showType = None):
    """
    displays either all root categories, or the contents of a category.
    the contents of a category could be other categories or forum threads.

    TODO: clean this mess up - sorry for everyone who trys to understand
    this function - this is is probably the oldest and ugliest in 
    the whole SCT source.
    """
    args = {
        'group__isnull': True,
        'parent__isnull': True,
        }
    categoryObject = None
    
    sphdata = get_current_sphdata()
    
    if category_id != None and category_id != '0':
        args['parent__isnull'] = False
        args['parent'] = category_id
        categoryObject = get_object_or_404(Category, pk = category_id)
        if not categoryObject.has_view_permission( request.user ):
            raise PermissionDenied()
        categoryObject.touch(request.session, request.user)
        blog_feed_url = reverse('sphboard-feeds', urlconf=get_current_urlconf(), args = (), kwargs = { 'url': 'latest/2' })
        add_rss_feed( blog_feed_url, 'Latest Threads in %s RSS Feed' % categoryObject.name )

        if sphdata != None: sphdata['subtitle'] = categoryObject.name
        
    if group != None:
        args['group__isnull'] = False
        args['group'] = group

    if showType == 'threads':
        categories = []
    else:
        if 'group' in args:
            categories = Category.sph_objects.filter( group = args['group'] )#filter_for_group( args['group'] )
            if 'parent' in args:
                categories = categories.filter( parent = category_id )
            else:
                categories = categories.filter( parent__isnull = True )
            categories = [ category for category in categories if category.has_view_permission( request.user ) ]
        else:
            categories = Category.objects.filter( **args )
    
    context = { 'rootCategories': categories,
                'category': categoryObject,
                'allowPostThread': categoryObject and categoryObject.allowPostThread( request.user ),
                'category_id': category_id, }

    try:
        context['search_posts_url'] = sph_reverse('sphsearchboard_posts')
    except:
        pass

    templateName = 'sphene/sphboard/listCategories.html'
    if categoryObject == None:
        if showType != 'threads':
            return render_to_response( templateName, context,
                                       context_instance = RequestContext(request) )
        
        ## Show the latest threads from all categories.
        allowed_categories = get_all_viewable_categories( group, request.user )
        
        if group != None: thread_args = { 'category__group': group }
        else: thread_args = { 'category__group__isnull': True }
        #thread_args[ 'thread__isnull'] = True
        thread_args[ 'category__id__in'] = allowed_categories
        context['isShowLatest'] = True
        thread_list = ThreadInformation.objects.filter( **thread_args )
    else:
        category_type = categoryObject.get_category_type()
        templateName = category_type.get_threadlist_template()
        thread_list = categoryObject.get_thread_list()

    #thread_list = thread_list.extra( select = { 'latest_postdate': 'SELECT MAX(postdate) FROM sphboard_post AS postinthread WHERE postinthread.thread_id = sphboard_post.id OR postinthread.id = sphboard_post.id', 'is_sticky': 'status & %d' % POST_STATUSES['sticky'] } )
    if showType != 'threads':
        thread_list = thread_list.order_by( '-sticky_value', '-thread_latest_postdate' )
    else:
        thread_list = thread_list.order_by( '-thread_latest_postdate' )

    res =  object_list( request = request,
                        queryset = thread_list,
                        template_name = templateName,
                        extra_context = context,
                        template_object_name = 'thread',
                        allow_empty = True,
                        paginate_by = 10,
                        )
    
    res.sph_lastmodified = True
    return res
Example #54
0
def profile_edit(request, group, user_id):
    requester = request.user

    if user_id:
        user = get_object_or_404(User, pk=user_id)
    else:
        user = requester

    if user is None or user != requester or not requester.is_authenticated:
        if not (requester and requester.is_authenticated and (
                requester.is_superuser or has_permission_flag(requester, 'community_manage_users'))):
            raise PermissionDenied()

    if request.method == 'POST':
        reqdata = request.POST.copy()
        reqdata.update(request.FILES)
        form = EditProfileForm(user, request.POST, request.FILES)
    else:
        form = EditProfileForm(user)

    profile_edit_init_form.send(sender=EditProfileForm,
                                instance=form,
                                request=request,
                                )

    if request.method == 'POST':
        if form.is_valid():
            data = form.cleaned_data
            user.first_name = data['first_name']
            user.last_name = data['last_name']

            if user.email != data['email_address']:
                email_address = data['email_address']
                mail_domain = email_address.split('@')[1]
                logger.info('change e-mail request ip: %s, email: %s' % (get_client_ip(request), email_address))

                s = URLSafeTimedSerializer(getattr(settings, 'EMAIL_CHANGE_SECRET', '87fuhaidfhahfokhh3u'))
                email_change_hash = s.dumps({'email': email_address,
                                             'user_id': user.pk})

                # do not tell spammers that we have not sent email :)
                if mail_domain not in getattr(settings, 'BLACKLISTED_EMAIL_DOMAINS', []):
                    if not group:
                        subject = ugettext(u'Email verification required')
                    else:
                        subject = ugettext(u'Email verification required for site %(site_name)s') % {
                            'site_name': group.get_name()}

                    mail_context = RequestContext(request, {
                        'email': email_address,
                        'baseurl': group.baseurl,
                        'path': sph_reverse('sphene.community.views.email_change_hash', (),
                                            {"email_change_hash": email_change_hash}),
                        'group': group,
                    })
                    text_part = loader.get_template(
                        'sphene/community/accounts/account_email_change.txt') \
                        .render(mail_context)
                    html_part = loader.get_template(
                        'sphene/community/accounts/account_email_change.html') \
                        .render(mail_context)

                    msg = EmailMultiAlternatives(subject, text_part, None, [email_address])
                    msg.attach_alternative(html_part, "text/html")
                    msg.send()
                    messages.info(request, message=ugettext(
                        u'E-mail with verification link has been sent to change your e-mail address.'))

            if data['new_password']:
                # Check was already made in form, we only need to change the password.
                user.set_password(data['new_password'])

            profile_edit_save_form.send(sender=EditProfileForm,
                                        instance=form,
                                        request=request,
                                        )

            user.save()
            messages.success(request, message=ugettext(u'Successfully changed user profile.'))

            return HttpResponseRedirect(sph_user_profile_link(user))

    else:
        form.fields['first_name'].initial = user.first_name
        form.fields['last_name'].initial = user.last_name
        form.fields['email_address'].initial = user.email

    """
    form = EditProfileForm( { 'first_name': user.first_name,
                              'last_name': user.last_name,
                              'email_address': user.email,
                              } )
    """

    return render(
        request,
        'sphene/community/profile_edit.html',
        {'profile_user': user,
         'form': form,
         'is_sphboard': 'sphene.sphboard' in settings.INSTALLED_APPS
        }
    )
def showCategory(request, group, category_id=None, showType=None, slug=None):
    """
    displays either all root categories, or the contents of a category.
    the contents of a category could be other categories or forum threads.

    TODO: clean this mess up - sorry for everyone who trys to understand
    this function - this is is probably the oldest and ugliest in 
    the whole SCT source.

    We no longer support having no group !!
    """
    args = {"group__isnull": True, "parent__isnull": True}
    categoryObject = None

    sphdata = get_current_sphdata()

    if category_id != None and category_id != "0":
        args["parent__isnull"] = False
        args["parent"] = category_id
        categoryObject = get_object_or_404(Category, pk=category_id)
        if not categoryObject.has_view_permission(request.user):
            raise PermissionDenied()
        categoryObject.touch(request.session, request.user)
        blog_feed_url = sph_reverse("sphboard-feeds", kwargs={"url": "latest/%s" % categoryObject.id})
        add_rss_feed(blog_feed_url, "Latest Threads in %s RSS Feed" % categoryObject.name)

        if sphdata != None:
            sphdata["subtitle"] = categoryObject.name
    elif sphdata is not None:
        sphdata["subtitle"] = ugettext("Forum Overview")

    if group != None:
        args["group__isnull"] = False
        args["group"] = group

    if showType == "threads":
        categories = []
    else:
        if "group" in args:
            categories = Category.sph_objects.filter(group=args["group"])  # filter_for_group( args['group'] )
            if "parent" in args:
                categories = categories.filter(parent=category_id)
            else:
                categories = categories.filter(parent__isnull=True)
            categories = [category for category in categories if category.has_view_permission(request.user)]
        else:
            categories = Category.objects.filter(**args)

    context = {
        "rootCategories": categories,
        "category": categoryObject,
        "allowPostThread": categoryObject and categoryObject.allowPostThread(request.user),
        "category_id": category_id,
    }

    try:
        context["search_posts_url"] = sph_reverse("sphsearchboard_posts")
    except:
        pass

    templateName = "sphene/sphboard/listCategories.html"
    if categoryObject == None:
        if showType != "threads":
            return render_to_response(templateName, context, context_instance=RequestContext(request))

        ## Show the latest threads from all categories.
        allowed_categories = get_all_viewable_categories(group, request.user)

        if group != None:
            thread_args = {"category__group": group}
        else:
            thread_args = {"category__group__isnull": True}
        # thread_args[ 'thread__isnull'] = True
        thread_args["category__id__in"] = allowed_categories
        context["isShowLatest"] = True
        thread_list = ThreadInformation.objects.filter(**thread_args)
    else:
        category_type = categoryObject.get_category_type()
        templateName = category_type.get_threadlist_template()
        thread_list = categoryObject.get_thread_list()

    # thread_list = thread_list.extra( select = { 'latest_postdate': 'SELECT MAX(postdate) FROM sphboard_post AS postinthread WHERE postinthread.thread_id = sphboard_post.id OR postinthread.id = sphboard_post.id', 'is_sticky': 'status & %d' % POST_STATUSES['sticky'] } )
    if showType != "threads":
        thread_list = thread_list.order_by("-sticky_value", "-thread_latest_postdate")
    else:
        thread_list = thread_list.order_by("-thread_latest_postdate")

    res = object_list(
        request=request,
        queryset=thread_list,
        template_name=templateName,
        extra_context=context,
        template_object_name="thread",
        allow_empty=True,
        paginate_by=10,
    )

    res.sph_lastmodified = True
    return res
Example #56
0
 def get_absolute_editurl(self):
     return sph_reverse('sphwiki_editversion',
                        kwargs={
                            'snipName': self.snip.name,
                            'versionId': self.id
                        })
Example #57
0
def showCategory(request, group, category_id=None, showType=None, slug=None):
    """
    displays either all root categories, or the contents of a category.
    the contents of a category could be other categories or forum threads.

    TODO: clean this mess up - sorry for everyone who trys to understand
    this function - this is is probably the oldest and ugliest in
    the whole SCT source.

    We no longer support having no group !!
    """
    args = {
        'group__isnull': True,
        'parent__isnull': True,
    }
    categoryObject = None

    sphdata = get_current_sphdata()

    if category_id != None and category_id != '0':
        args['parent__isnull'] = False
        args['parent'] = category_id
        categoryObject = get_object_or_404(Category, pk=category_id)
        if not categoryObject.has_view_permission(request.user):
            raise PermissionDenied()
        categoryObject.touch(request.session, request.user)
        blog_feed_url = sph_reverse('sphboard-feeds',
                                    kwargs={'category_id': categoryObject.id})
        add_rss_feed(blog_feed_url,
                     'Latest Threads in %s RSS Feed' % categoryObject.name)

        if sphdata != None: sphdata['subtitle'] = categoryObject.name
    elif sphdata is not None:
        sphdata['subtitle'] = ugettext('Forum Overview')

    if group != None:
        args['group__isnull'] = False
        args['group'] = group

    if showType == 'threads':
        categories = []
    else:
        if 'group' in args:
            categories = Category.sph_objects.filter(
                group=args['group'])  #filter_for_group( args['group'] )
            if 'parent' in args:
                categories = categories.filter(parent=category_id)
            else:
                categories = categories.filter(parent__isnull=True)
            categories = [
                category for category in categories
                if category.has_view_permission(request.user)
            ]
        else:
            categories = Category.objects.filter(**args)

    context = {
        'rootCategories':
        categories,
        'category':
        categoryObject,
        'allowPostThread':
        categoryObject and categoryObject.allowPostThread(request.user),
        'category_id':
        category_id,
    }

    try:
        context['search_posts_url'] = sph_reverse('sphsearchboard_posts')
    except:
        pass

    templateName = 'sphene/sphboard/listCategories.html'
    if categoryObject == None:
        if showType != 'threads':
            return render_to_response(templateName,
                                      context,
                                      context_instance=RequestContext(request))

        ## Show the latest threads from all categories.
        allowed_categories = get_all_viewable_categories(group, request.user)

        if group != None: thread_args = {'category__group': group}
        else: thread_args = {'category__group__isnull': True}
        #thread_args[ 'thread__isnull'] = True
        thread_args['category__id__in'] = allowed_categories
        thread_args['root_post__is_hidden'] = 0
        context['isShowLatest'] = True
        thread_list = ThreadInformation.objects.filter(**thread_args)
    else:
        category_type = categoryObject.get_category_type()
        templateName = category_type.get_threadlist_template()
        thread_list = categoryObject.get_thread_list()

    #thread_list = thread_list.extra( select = { 'latest_postdate': 'SELECT MAX(postdate) FROM sphboard_post AS postinthread WHERE postinthread.thread_id = sphboard_post.id OR postinthread.id = sphboard_post.id', 'is_sticky': 'status & %d' % POST_STATUSES['sticky'] } )
    if showType != 'threads':
        thread_list = thread_list.order_by('-sticky_value',
                                           '-thread_latest_postdate')
    else:
        thread_list = thread_list.order_by('-thread_latest_postdate')
    thread_list = thread_list.select_related('root_post', 'latest_post',
                                             'root_post__category',
                                             'root_post__author',
                                             'latest_post__author')

    res = object_list(
        request=request,
        queryset=thread_list,
        template_name=templateName,
        extra_context=context,
        template_object_name='thread',
        allow_empty=True,
        paginate_by=10,
    )

    res.sph_lastmodified = True
    return res
Example #58
0
def sph_user_profile_link(value):
    """ Returns the URL to the user profile. """
    kwargs = {
        'user_id': value.id,
    }
    return sph_reverse('sph_profile', kwargs=kwargs)
Example #59
0
def edit_block_config(request, group, block_config_id):
    if request.method == 'GET' and 'delete' in request.GET:
        BlockConfiguration.objects.get( pk = block_config_id ).delete()
        return HttpResponseRedirect( sph_reverse( 'sphblockframework_config' ) )

    return None
Example #60
0
def profile_edit(request, group, user_id):
    requester = request.user

    if user_id:
        user = get_object_or_404(User, pk=user_id)
    else:
        user = requester

    if user is None or user != requester or not requester.is_authenticated:
        if not (requester and requester.is_authenticated and
                (requester.is_superuser
                 or has_permission_flag(requester, 'community_manage_users'))):
            raise PermissionDenied()

    if request.method == 'POST':
        reqdata = request.POST.copy()
        reqdata.update(request.FILES)
        form = EditProfileForm(user, request.POST, request.FILES)
    else:
        form = EditProfileForm(user)

    profile_edit_init_form.send(
        sender=EditProfileForm,
        instance=form,
        request=request,
    )

    if request.method == 'POST':
        if form.is_valid():
            data = form.cleaned_data
            user.first_name = data['first_name']
            user.last_name = data['last_name']

            if user.email != data['email_address']:
                email_address = data['email_address']
                mail_domain = email_address.split('@')[1]
                logger.info('change e-mail request ip: %s, email: %s' %
                            (get_client_ip(request), email_address))

                s = URLSafeTimedSerializer(
                    getattr(settings, 'EMAIL_CHANGE_SECRET',
                            '87fuhaidfhahfokhh3u'))
                email_change_hash = s.dumps({
                    'email': email_address,
                    'user_id': user.pk
                })

                # do not tell spammers that we have not sent email :)
                if mail_domain not in getattr(settings,
                                              'BLACKLISTED_EMAIL_DOMAINS', []):
                    if not group:
                        subject = ugettext(u'Email verification required')
                    else:
                        subject = ugettext(
                            u'Email verification required for site %(site_name)s'
                        ) % {
                            'site_name': group.get_name()
                        }

                    mail_context = RequestContext(
                        request, {
                            'email':
                            email_address,
                            'baseurl':
                            group.baseurl,
                            'path':
                            sph_reverse(
                                'sphene.community.views.email_change_hash',
                                (), {"email_change_hash": email_change_hash}),
                            'group':
                            group,
                        })
                    text_part = loader.get_template(
                        'sphene/community/accounts/account_email_change.txt') \
                        .render(mail_context)
                    html_part = loader.get_template(
                        'sphene/community/accounts/account_email_change.html') \
                        .render(mail_context)

                    msg = EmailMultiAlternatives(subject, text_part, None,
                                                 [email_address])
                    msg.attach_alternative(html_part, "text/html")
                    msg.send()
                    messages.info(
                        request,
                        message=ugettext(
                            u'E-mail with verification link has been sent to change your e-mail address.'
                        ))

            if data['new_password']:
                # Check was already made in form, we only need to change the password.
                user.set_password(data['new_password'])

            profile_edit_save_form.send(
                sender=EditProfileForm,
                instance=form,
                request=request,
            )

            user.save()
            messages.success(
                request,
                message=ugettext(u'Successfully changed user profile.'))

            return HttpResponseRedirect(sph_user_profile_link(user))

    else:
        form.fields['first_name'].initial = user.first_name
        form.fields['last_name'].initial = user.last_name
        form.fields['email_address'].initial = user.email
    """
    form = EditProfileForm( { 'first_name': user.first_name,
                              'last_name': user.last_name,
                              'email_address': user.email,
                              } )
    """

    return render(
        request, 'sphene/community/profile_edit.html', {
            'profile_user': user,
            'form': form,
            'is_sphboard': 'sphene.sphboard' in settings.INSTALLED_APPS
        })