Пример #1
0
    def perform_create(self, title, user, subtitle=""):
        """Create gallery

        :param title: title
        :type title: str
        :param user:  the user
        :type user: zds.member.models.User
        :param subtitle: subtitle
        :type subtitle: str
        :rtype: Gallery
        """
        gallery = Gallery(title=title)
        gallery.subtitle = subtitle
        gallery.slug = slugify(title)
        gallery.pubdate = datetime.datetime.now()
        gallery.save()

        user_gallery = UserGallery(gallery=gallery,
                                   user=user,
                                   mode=GALLERY_WRITE)
        user_gallery.save()

        self.gallery = gallery
        self.users_and_permissions = {user.pk: {"read": True, "write": True}}

        return self.gallery
Пример #2
0
    def perform_add_user(self, user, can_write=False):
        """Add user to gallery

        :param user:  the user
        :type user: zds.member.models.User
        :param can_write: write permission ?
        :type can_write: bool
        """

        mode = GALLERY_WRITE if can_write else GALLERY_READ
        if user.pk not in self.users_and_permissions:
            user_gallery = UserGallery(user=user, gallery=self.gallery, mode=mode)
            user_gallery.save()
            self.users_and_permissions[user.pk] = {"read": True, "write": can_write}
            return user_gallery
        else:
            raise UserAlreadyInGallery()
Пример #3
0
    def set_avatar_from_file(self, avatar, filename='avatar.png'):
        """
        Updates the avatar of this user from a file, creating a gallery on his account
        if needed and adding the avatar to the gallery.
        :param avatar: The avatar file (file-like object).
        :param filename: The file name, including the type extension.
        """
        user_gallery = UserGallery.objects.filter(gallery__title=ZDS_APP['gallery']['avatars_gallery'], user=self.user)\
            .first()

        if not user_gallery:
            gallery = Gallery()
            gallery.title = ZDS_APP['gallery']['avatars_gallery']
            gallery.subtitle = ''
            gallery.slug = slugify(ZDS_APP['gallery']['avatars_gallery'])
            gallery.pubdate = datetime.now()
            gallery.save()

            user_gallery = UserGallery()
            user_gallery.gallery = gallery
            user_gallery.mode = GALLERY_WRITE
            user_gallery.user = self.user
            user_gallery.save()

        image = Image()
        image.title = _('Avatar')
        image.legend = _('Avatar importé')
        image.gallery = user_gallery.gallery
        image.physical = get_thumbnailer(avatar, relative_name=filename)
        image.pubdate = datetime.now()
        image.save()

        self.avatar_url = image.get_absolute_url()
Пример #4
0
def new_gallery(request):
    '''
    Creates a new gallery
    '''
    if request.method == 'POST':
        form = GalleryForm(request.POST)
        if form.is_valid():
            data = form.data
            # Creating the gallery
            gal = Gallery()
            gal.title = data['title']
            gal.subtitle = data['subtitle']
            gal.slug = slugify(data['title'])
            gal.pubdate = datetime.now()
            gal.save()

            # Attach user
            userg = UserGallery()
            userg.gallery = gal
            userg.mode = 'W'
            userg.user = request.user
            userg.save()

            return redirect(gal.get_absolute_url())

        else:
            # TODO: add errors to the form and return it
            raise Http404
    else:
        form = GalleryForm()
        return render_template('gallery/new_gallery.html', {
            'form': form
        })
Пример #5
0
def new_gallery(request):
    """Creates a new gallery."""

    if request.method == "POST":
        form = GalleryForm(request.POST)
        if form.is_valid():
            data = form.data

            # Creating the gallery

            gal = Gallery()
            gal.title = data["title"]
            gal.subtitle = data["subtitle"]
            gal.slug = slugify(data["title"])
            gal.pubdate = datetime.now()
            gal.save()

            # Attach user

            userg = UserGallery()
            userg.gallery = gal
            userg.mode = "W"
            userg.user = request.user
            userg.save()
            return redirect(gal.get_absolute_url())
        else:
            return render_template("gallery/gallery/new.html", {"form": form})
    else:
        form = GalleryForm()
        return render_template("gallery/gallery/new.html", {"form": form})
Пример #6
0
def _get_content_gallery(content_pk, user):
    content = PublishableContent.objects.filter(pk=content_pk).first()
    if not content or user not in content.authors.all():
        return {}
    content_gallery = content.gallery
    if not content_gallery:
        content.gallery = Gallery(title=content.title, subtitle=content.description, slug=content.slug)
        content.gallery.save()
        content_gallery = content.gallery
        for author in content.authors.all():
            UserGallery(user=author, gallery=content.gallery, mode=GALLERY_WRITE).save()
    return {'auto_update_gallery': content_gallery}
Пример #7
0
def _get_default_gallery(user):
    if not user or not user.is_authenticated:
        return {}

    user_default_gallery = UserGallery.objects.filter(user=user, is_default=True).first()
    if not user_default_gallery:
        gallery = Gallery(title=_('Galerie par défaut'), subtitle='', slug=_('galerie-par-default'))
        gallery.save()
        UserGallery(user=user, is_default=True, gallery=gallery, mode=GALLERY_WRITE).save()
    else:
        gallery = user_default_gallery.gallery
    return {'auto_update_gallery': gallery}
Пример #8
0
def new_gallery(request):
    """Creates a new gallery."""

    if request.method == "POST":
        form = GalleryForm(request.POST)
        if form.is_valid():
            data = form.data

            # Creating the gallery

            gal = Gallery()
            gal.title = data["title"]
            gal.subtitle = data["subtitle"]
            gal.slug = slugify(data["title"])
            gal.pubdate = datetime.now()
            gal.save()

            # Attach user

            userg = UserGallery()
            userg.gallery = gal
            userg.mode = "W"
            userg.user = request.user
            userg.save()
            return redirect(gal.get_absolute_url())
        else:
            return render_template("gallery/gallery/new.html", {"form": form})
    else:
        form = GalleryForm()
        return render_template("gallery/gallery/new.html", {"form": form})
Пример #9
0
    def form_valid(self, form):

        _type = _("de l'article")

        if self.object.is_tutorial:
            _type = _("du tutoriel")
        elif self.object.is_opinion:
            _type = _("du billet")

        bot = get_object_or_404(
            User, username=settings.ZDS_APP["member"]["bot_account"])
        all_authors_pk = [author.pk for author in self.object.authors.all()]
        for user in form.cleaned_data["users"]:
            if user.pk not in all_authors_pk:
                self.object.authors.add(user)
                if self.object.validation_private_message:
                    self.object.validation_private_message.add_participant(
                        user)
                all_authors_pk.append(user.pk)
                if user != self.request.user:
                    url_index = reverse(self.object.type.lower() + ":find-" +
                                        self.object.type.lower(),
                                        args=[user.pk])
                    send_mp(
                        bot,
                        [user],
                        format_lazy("{}{}", _("Ajout à la rédaction "), _type),
                        self.versioned_object.title,
                        render_to_string(
                            "tutorialv2/messages/add_author_pm.md",
                            {
                                "content": self.object,
                                "type": _type,
                                "url": self.object.get_absolute_url(),
                                "index": url_index,
                                "user": user.username,
                            },
                        ),
                        hat=get_hat_from_settings("validation"),
                    )
                UserGallery(gallery=self.object.gallery,
                            user=user,
                            mode=GALLERY_WRITE).save()
                signals.authors_management.send(sender=self.__class__,
                                                content=self.object,
                                                performer=self.request.user,
                                                author=user,
                                                action="add")
        self.object.save()
        self.success_url = self.object.get_absolute_url()

        return super().form_valid(form)
Пример #10
0
def modify_gallery(request):
    '''Modify gallery instance'''

    if request.method != 'POST':
        raise Http404

    # Global actions

    if 'delete_multi' in request.POST:
        l = request.POST.getlist('items')

        perms = UserGallery.objects\
                .filter(gallery__pk__in=l, user=request.user, mode='W')\
                .count()

        # Check that the user has the RW right on each gallery
        if perms < len(l):
            raise Http404

        # Delete all the permissions on all the selected galleries
        UserGallery.objects.filter(gallery__pk__in=l).delete()
        # Delete all the images of the gallery (autodelete of file)
        Image.objects.filter(gallery__pk__in=l).delete()
        # Finally delete the selected galleries
        Gallery.objects.filter(pk__in=l).delete()

        return redirect(reverse('zds.gallery.views.gallery_list'))

    # Gallery-specific actions

    try:
        gal_pk = request.POST['gallery']
    except KeyError:
        raise Http404

    gal = get_object_or_404(Gallery, pk=gal_pk)
    gal_mode = get_object_or_404(UserGallery, gallery=gal, user=request.user)

    # Disallow actions to read-only members
    if gal_mode.mode != 'W':
        raise Http404

    if 'adduser' in request.POST:
        form = UserGalleryForm(request.POST)
        u = get_object_or_404(User, username=request.POST['user'])
        if form.is_valid():
            ug = UserGallery()
            ug.user = u
            ug.gallery = gal
            ug.mode = 'W'
            ug.save()


    return redirect(gal.get_absolute_url())
Пример #11
0
    def form_valid(self, form):
        gallery = Gallery()
        gallery.title = form.cleaned_data['title']
        gallery.subtitle = form.cleaned_data['subtitle']
        gallery.slug = slugify(form.cleaned_data['title'])
        gallery.pubdate = datetime.now()
        gallery.save()

        # Attach user :
        userg = UserGallery()
        userg.gallery = gallery
        userg.mode = 'W'
        userg.user = self.request.user
        userg.save()

        return HttpResponseRedirect(gallery.get_absolute_url())
Пример #12
0
 def ensure_author_gallery(self):
     """
     ensure all authors subscribe to gallery
     """
     author_set = UserGallery.objects.filter(user__in=list(self.authors.all()), gallery=self.gallery)\
         .values_list('user__pk', flat=True)
     for author in self.authors.all():
         if author.pk in author_set:
             continue
         user_gallery = UserGallery()
         user_gallery.gallery = self.gallery
         user_gallery.mode = GALLERY_WRITE  # write mode
         user_gallery.user = author
         user_gallery.save()
Пример #13
0
def create_gallery_for_article(content):
    # Creating the gallery
    gal = Gallery()
    gal.title = content.title
    gal.slug = slugify(content.title)
    gal.pubdate = datetime.now()
    gal.save()

    # Attach user to gallery
    for user in content.authors.all():
        userg = UserGallery()
        userg.gallery = gal
        userg.mode = "W"  # write mode
        userg.user = user
        userg.save()
    content.gallery = gal

    if not os.path.exists(gal.get_gallery_path()):
        os.makedirs(gal.get_gallery_path())

    return gal
Пример #14
0
def unregister(request):
    """allow members to unregister"""

    anonymous = get_object_or_404(
        User, username=settings.ZDS_APP["member"]["anonymous_account"])
    external = get_object_or_404(
        User, username=settings.ZDS_APP["member"]["external_account"])
    current = request.user
    for content in request.user.profile.get_contents():
        # we delete article only if not published with only one author
        if not content.in_public() and content.authors.count() == 1:
            if content.in_beta() and content.beta_topic:
                beta_topic = content.beta_topic
                beta_topic.is_locked = True
                beta_topic.save()
                first_post = beta_topic.first_post()
                first_post.update_content(
                    _(u"# Le tutoriel présenté par ce topic n\'existe plus."))
                first_post.save()
            content.delete()
        else:
            if content.authors.count() == 1:
                content.authors.add(external)
                external_gallery = UserGallery()
                external_gallery.user = external
                external_gallery.gallery = content.gallery
                external_gallery.mode = 'W'
                external_gallery.save()
                UserGallery.objects.filter(user=current).filter(
                    gallery=content.gallery).delete()

            content.authors.remove(current)
            content.save()
    # comments likes / dislikes
    for vote in CommentVote.objects.filter(user=current):
        if vote.positive:
            vote.comment.like -= 1
        else:
            vote.comment.dislike -= 1
        vote.comment.save()
        vote.delete()
    # all messages anonymisation (forum, article and tutorial posts)
    for message in Comment.objects.filter(author=current):
        message.author = anonymous
        message.save()
    for message in PrivatePost.objects.filter(author=current):
        message.author = anonymous
        message.save()
    # in case current has been moderator in his old day
    for message in Comment.objects.filter(editor=current):
        message.editor = anonymous
        message.save()
    for topic in PrivateTopic.objects.filter(author=current):
        topic.participants.remove(current)
        if topic.participants.count() > 0:
            topic.author = topic.participants.first()
            topic.participants.remove(topic.author)
            topic.save()
        else:
            topic.delete()
    for topic in PrivateTopic.objects.filter(participants__in=[current]):
        topic.participants.remove(current)
        topic.save()
    for topic in Topic.objects.filter(author=current):
        topic.author = anonymous
        topic.save()
    # Before deleting gallery let's summurize what we deleted
    # - unpublished tutorials with only the unregistering member as an author
    # - unpublished articles with only the unregistering member as an author
    # - all category associated with those entites (have a look on article.delete_entity_and_tree
    # and tutorial.delete_entity_and_tree
    # So concerning galleries, we just have for us
    # - "personnal galleries" with only one owner (unregistering user)
    # - "personnal galleries" with more than one owner
    # so we will just delete the unretistering user ownership and give it to anonymous in the only case
    # he was alone so that gallery is not lost
    for gallery in UserGallery.objects.filter(user=current):
        if gallery.gallery.get_linked_users().count() == 1:
            anonymous_gallery = UserGallery()
            anonymous_gallery.user = external
            anonymous_gallery.mode = "w"
            anonymous_gallery.gallery = gallery.gallery
            anonymous_gallery.save()
        gallery.delete()

    # remove API access (tokens + applications)
    for token in AccessToken.objects.filter(user=current):
        token.revoke()

    logout(request)
    User.objects.filter(pk=current.pk).delete()
    return redirect(reverse("homepage"))
Пример #15
0
def unregister(request):
    """allow members to unregister"""

    anonymous = get_object_or_404(
        User, username=settings.ZDS_APP["member"]["anonymous_account"])
    external = get_object_or_404(
        User, username=settings.ZDS_APP["member"]["external_account"])
    current = request.user
    for tuto in request.user.profile.get_tutos():
        # we delete article only if not published with only one author
        if not tuto.on_line() and tuto.authors.count() == 1:
            if tuto.in_beta():
                beta_topic = Topic.objects.get(key=tuto.pk)
                first_post = beta_topic.first_post()
                first_post.update_content(
                    _(u"# Le tutoriel présenté par ce topic n\'existe plus."))
            tuto.delete_entity_and_tree()
        else:
            if tuto.authors.count() == 1:
                tuto.authors.add(external)
                external_gallery = UserGallery()
                external_gallery.user = external
                external_gallery.gallery = tuto.gallery
                external_gallery.mode = 'W'
                external_gallery.save()
                UserGallery.objects.filter(user=current).filter(
                    gallery=tuto.gallery).delete()

            tuto.authors.remove(current)
            tuto.save()
    for article in request.user.profile.get_articles():
        # we delete article only if not published with only one author
        if not article.on_line() and article.authors.count() == 1:
            article.delete_entity_and_tree()
        else:
            if article.authors.count() == 1:
                article.authors.add(external)
            article.authors.remove(current)
            article.save()
    # comments likes / dislikes
    for like in CommentLike.objects.filter(user=current):
        like.comments.like -= 1
        like.comments.save()
        like.delete()
    for dislike in CommentDislike.objects.filter(user=current):
        dislike.comments.dislike -= 1
        dislike.comments.save()
        dislike.delete()
    # all messages anonymisation (forum, article and tutorial posts)
    for message in Comment.objects.filter(author=current):
        message.author = anonymous
        message.save()
    for message in PrivatePost.objects.filter(author=current):
        message.author = anonymous
        message.save()
    # in case current has been moderator in his old day
    for message in Comment.objects.filter(editor=current):
        message.editor = anonymous
        message.save()
    for topic in PrivateTopic.objects.filter(author=current):
        topic.participants.remove(current)
        if topic.participants.count() > 0:
            topic.author = topic.participants.first()
            topic.participants.remove(topic.author)
            topic.save()
        else:
            topic.delete()
    for topic in PrivateTopic.objects.filter(participants__in=[current]):
        topic.participants.remove(current)
        topic.save()
    for topic in Topic.objects.filter(author=current):
        topic.author = anonymous
        topic.save()
    TopicFollowed.objects.filter(user=current).delete()
    # Before deleting gallery let's summurize what we deleted
    # - unpublished tutorials with only the unregistering member as an author
    # - unpublished articles with only the unregistering member as an author
    # - all category associated with those entites (have a look on article.delete_entity_and_tree
    # and tutorial.delete_entity_and_tree
    # So concerning galleries, we just have for us
    # - "personnal galleries" with only one owner (unregistering user)
    # - "personnal galleries" with more than one owner
    # so we will just delete the unretistering user ownership and give it to anonymous in the only case
    # he was alone so that gallery is not lost
    for gallery in UserGallery.objects.filter(user=current):
        if gallery.gallery.get_linked_users().count() == 1:
            anonymous_gallery = UserGallery()
            anonymous_gallery.user = external
            anonymous_gallery.mode = "w"
            anonymous_gallery.gallery = gallery.gallery
            anonymous_gallery.save()
        gallery.delete()

    logout(request)
    User.objects.filter(pk=current.pk).delete()
    return redirect(reverse("zds.pages.views.home"))
Пример #16
0
def unregister(request):
    """allow members to unregister"""

    anonymous = get_object_or_404(
        User, username=settings.ZDS_APP['member']['anonymous_account'])
    external = get_object_or_404(
        User, username=settings.ZDS_APP['member']['external_account'])
    current = request.user
    # Nota : as of v21 all about content paternity is held by a proper receiver in zds.tutorialv2.models.models_database
    # comments likes / dislikes
    for vote in CommentVote.objects.filter(user=current):
        if vote.positive:
            vote.comment.like -= 1
        else:
            vote.comment.dislike -= 1
        vote.comment.save()
        vote.delete()
    # all messages anonymisation (forum, article and tutorial posts)
    for message in Comment.objects.filter(author=current):
        message.author = anonymous
        message.save()
    for message in PrivatePost.objects.filter(author=current):
        message.author = anonymous
        message.save()
    # karma notes, alerts and sanctions anonymisation (to keep them)
    for note in KarmaNote.objects.filter(moderator=current):
        note.moderator = anonymous
        note.save()
    for ban in Ban.objects.filter(moderator=current):
        ban.moderator = anonymous
        ban.save()
    for alert in Alert.objects.filter(author=current):
        alert.author = anonymous
        alert.save()
    for alert in Alert.objects.filter(moderator=current):
        alert.moderator = anonymous
        alert.save()
    # in case current has been moderator in his old day
    for message in Comment.objects.filter(editor=current):
        message.editor = anonymous
        message.save()
    for topic in PrivateTopic.objects.filter(author=current):
        topic.participants.remove(current)
        if topic.participants.count() > 0:
            topic.author = topic.participants.first()
            topic.participants.remove(topic.author)
            topic.save()
        else:
            topic.delete()
    for topic in PrivateTopic.objects.filter(participants__in=[current]):
        topic.participants.remove(current)
        topic.save()
    for topic in Topic.objects.filter(author=current):
        topic.author = anonymous
        topic.save()
    # Before deleting gallery let's summurize what we deleted
    # - unpublished tutorials with only the unregistering member as an author
    # - unpublished articles with only the unregistering member as an author
    # - all category associated with those entites (have a look on article.delete_entity_and_tree
    # and tutorial.delete_entity_and_tree
    # So concerning galleries, we just have for us
    # - "personnal galleries" with only one owner (unregistering user)
    # - "personnal galleries" with more than one owner
    # so we will just delete the unretistering user ownership and give it to anonymous in the only case
    # he was alone so that gallery is not lost
    for gallery in UserGallery.objects.filter(user=current):
        if gallery.gallery.get_linked_users().count() == 1:
            anonymous_gallery = UserGallery()
            anonymous_gallery.user = external
            anonymous_gallery.mode = 'w'
            anonymous_gallery.gallery = gallery.gallery
            anonymous_gallery.save()
        gallery.delete()

    # remove API access (tokens + applications)
    for token in AccessToken.objects.filter(user=current):
        token.revoke()

    logout(request)
    User.objects.filter(pk=current.pk).delete()
    return redirect(reverse('homepage'))
Пример #17
0
def modify_gallery(request):
    """Modify gallery instance: delete galleries or add user to them"""

    # Global actions

    if 'delete_multi' in request.POST:
        list_items = request.POST.getlist('items')

        # Don't delete gallery when it's link to tutorial
        free_galleries = []
        for g_pk in list_items:

            # check if the gallery is not linked to a content
            v2_content = PublishableContent.objects.filter(
                gallery__pk=g_pk).first()
            has_v2_content = v2_content is not None
            if has_v2_content:
                gallery = Gallery.objects.get(pk=g_pk)
                _type = _(u'au tutoriel')
                if v2_content.type == 'ARTICLE':
                    _type = _(u"à l'article")
                error_message = _(u'La galerie « {} » ne peut pas être supprimée car elle est liée {} « {} ».')\
                    .format(gallery.title, _type, v2_content.title)
                messages.error(request, error_message)
            else:
                free_galleries.append(g_pk)

        perms = UserGallery.objects.filter(gallery__pk__in=free_galleries,
                                           user=request.user,
                                           mode='W').count()

        # Check that the user has the RW right on each gallery

        if perms < len(free_galleries):
            raise PermissionDenied

        # Delete all the permissions on all the selected galleries

        UserGallery.objects.filter(gallery__pk__in=free_galleries).delete()

        # Delete all the images of the gallery (autodelete of file)

        Image.objects.filter(gallery__pk__in=free_galleries).delete()

        # Finally delete the selected galleries

        Gallery.objects.filter(pk__in=free_galleries).delete()
        return redirect(reverse('gallery-list'))
    elif 'adduser' in request.POST:

        # Gallery-specific actions

        try:
            gal_pk = request.POST['gallery']
        except KeyError:
            raise Http404
        gallery = get_object_or_404(Gallery, pk=gal_pk)

        # Disallow actions to read-only members

        try:
            gal_mode = UserGallery.objects.get(gallery=gallery,
                                               user=request.user)
            if gal_mode.mode != 'W':
                raise PermissionDenied
        except:
            raise PermissionDenied
        form = UserGalleryForm(request.POST)
        if form.is_valid():
            user = get_object_or_404(User, username=request.POST['user'])

            # If a user is already in a user gallery, we don't add him.

            galleries = UserGallery.objects.filter(gallery=gallery,
                                                   user=user).all()
            if galleries.count() > 0:
                return redirect(gallery.get_absolute_url())
            if user.profile.is_private():
                return redirect(gallery.get_absolute_url())
            user_gal = UserGallery()
            user_gal.user = user
            user_gal.gallery = gallery
            user_gal.mode = request.POST['mode']
            user_gal.save()
        else:
            return render(
                request, 'gallery/gallery/details.html', {
                    'gallery': gallery,
                    'gallery_mode': gal_mode,
                    'images': gallery.get_images(),
                    'form': form,
                })
        return redirect(gallery.get_absolute_url())
Пример #18
0
def modify_gallery(request):
    """Modify gallery instance."""

    # Global actions

    if "delete_multi" in request.POST:
        l = request.POST.getlist("items")
        
        # Don't delete gallery when it's link to tutorial
        free_galleries = []
        for g_pk in l:
            if Tutorial.objects.filter(gallery__pk=g_pk).exists():
                gallery = Gallery.objects.get(pk=g_pk)
                messages.error(request, "La galerie '{}' ne peut pas être supprimée car elle est liée à un tutoriel existant".format(gallery.title))
            else:
                free_galleries.append(g_pk)
        
        perms = UserGallery.objects.filter(gallery__pk__in=free_galleries,
                                           user=request.user, mode="W").count()

        # Check that the user has the RW right on each gallery

        if perms < len(free_galleries):
            raise PermissionDenied

        # Delete all the permissions on all the selected galleries

        UserGallery.objects.filter(gallery__pk__in=free_galleries).delete()

        # Delete all the images of the gallery (autodelete of file)

        Image.objects.filter(gallery__pk__in=free_galleries).delete()

        # Finally delete the selected galleries

        Gallery.objects.filter(pk__in=free_galleries).delete()
        return redirect(reverse("zds.gallery.views.gallery_list"))
    elif "adduser" in request.POST:

        # Gallery-specific actions

        try:
            gal_pk = request.POST["gallery"]
        except KeyError:
            raise Http404
        gallery = get_object_or_404(Gallery, pk=gal_pk)

        # Disallow actions to read-only members

        try:
            gal_mode = UserGallery.objects.get(gallery=gallery,
                                               user=request.user)
            if gal_mode.mode != "W":
                raise PermissionDenied
        except:
            raise PermissionDenied
        form = UserGalleryForm(request.POST)
        if form.is_valid():
            user = get_object_or_404(User, username=request.POST["user"])

            # If a user is already in a user gallery, we don't add him.

            galleries = UserGallery.objects.filter(gallery=gallery,
                                                   user=user).all()
            if galleries.count() > 0:
                return redirect(gallery.get_absolute_url())
            ug = UserGallery()
            ug.user = user
            ug.gallery = gallery
            ug.mode = request.POST["mode"]
            ug.save()
        else:
            return render_template("gallery/gallery/details.html", {
                "gallery": gallery,
                "gallery_mode": gal_mode,
                "images": gallery.get_images(),
                "form": form,
            })
    return redirect(gallery.get_absolute_url())
Пример #19
0
def unregister(request):
    """Allow members to unregister."""

    anonymous = get_object_or_404(User, username=settings.ZDS_APP['member']['anonymous_account'])
    external = get_object_or_404(User, username=settings.ZDS_APP['member']['external_account'])
    current = request.user
    # Nota : as of v21 all about content paternity is held by a proper receiver in zds.tutorialv2.models.database
    PickListOperation.objects.filter(staff_user=current).update(staff_user=anonymous)
    PickListOperation.objects.filter(canceler_user=current).update(canceler_user=anonymous)
    # Comments likes / dislikes
    votes = CommentVote.objects.filter(user=current)
    for vote in votes:
        if vote.positive:
            vote.comment.like -= 1
        else:
            vote.comment.dislike -= 1
        vote.comment.save()
    votes.delete()
    # All contents anonymization
    Comment.objects.filter(author=current).update(author=anonymous)
    PrivatePost.objects.filter(author=current).update(author=anonymous)
    CommentEdit.objects.filter(editor=current).update(editor=anonymous)
    CommentEdit.objects.filter(deleted_by=current).update(deleted_by=anonymous)
    # Karma notes, alerts and sanctions anonymization (to keep them)
    KarmaNote.objects.filter(moderator=current).update(moderator=anonymous)
    Ban.objects.filter(moderator=current).update(moderator=anonymous)
    Alert.objects.filter(author=current).update(author=anonymous)
    Alert.objects.filter(moderator=current).update(moderator=anonymous)
    BannedEmailProvider.objects.filter(moderator=current).update(moderator=anonymous)
    # Solved hat requests anonymization
    HatRequest.objects.filter(moderator=current).update(moderator=anonymous)
    # In case current user has been moderator in the past
    Comment.objects.filter(editor=current).update(editor=anonymous)
    for topic in PrivateTopic.objects.filter(author=current):
        topic.participants.remove(current)
        if topic.participants.count() > 0:
            topic.author = topic.participants.first()
            topic.participants.remove(topic.author)
            topic.save()
        else:
            topic.delete()
    for topic in PrivateTopic.objects.filter(participants__in=[current]):
        topic.participants.remove(current)
        topic.save()
    Topic.objects.filter(solved_by=current).update(solved_by=anonymous)
    Topic.objects.filter(author=current).update(author=anonymous)

    # Any content exclusively owned by the unregistering member will
    # be deleted just before the User object (using a pre_delete
    # receiver).
    #
    # Regarding galleries, there are two cases:
    #
    # - "personal galleries" with one owner (the unregistering
    #   user). The user's ownership is removed and replaced by an
    #   anonymous user in order not to lost the gallery.
    #
    # - "personal galleries" with many other owners. It is safe to
    #   remove the user's ownership, the gallery won't be lost.

    galleries = UserGallery.objects.filter(user=current)
    for gallery in galleries:
        if gallery.gallery.get_linked_users().count() == 1:
            anonymous_gallery = UserGallery()
            anonymous_gallery.user = external
            anonymous_gallery.mode = 'w'
            anonymous_gallery.gallery = gallery.gallery
            anonymous_gallery.save()
    galleries.delete()

    # Remove API access (tokens + applications)
    for token in AccessToken.objects.filter(user=current):
        token.revoke()

    logout(request)
    User.objects.filter(pk=current.pk).delete()
    return redirect(reverse('homepage'))
Пример #20
0
def unregister(request):
    """Allow members to unregister."""

    anonymous = get_object_or_404(User, username=settings.ZDS_APP["member"]["anonymous_account"])
    external = get_object_or_404(User, username=settings.ZDS_APP["member"]["external_account"])
    current = request.user
    # Nota : as of v21 all about content paternity is held by a proper receiver in zds.tutorialv2.models.database
    PickListOperation.objects.filter(staff_user=current).update(staff_user=anonymous)
    PickListOperation.objects.filter(canceler_user=current).update(canceler_user=anonymous)
    # Comments likes / dislikes
    votes = CommentVote.objects.filter(user=current)
    for vote in votes:
        if vote.positive:
            vote.comment.like -= 1
        else:
            vote.comment.dislike -= 1
        vote.comment.save()
    votes.delete()
    # All contents anonymization
    Comment.objects.filter(author=current).update(author=anonymous)
    PrivatePost.objects.filter(author=current).update(author=anonymous)
    CommentEdit.objects.filter(editor=current).update(editor=anonymous)
    CommentEdit.objects.filter(deleted_by=current).update(deleted_by=anonymous)
    # Karma notes, alerts and sanctions anonymization (to keep them)
    KarmaNote.objects.filter(moderator=current).update(moderator=anonymous)
    Ban.objects.filter(moderator=current).update(moderator=anonymous)
    Alert.objects.filter(author=current).update(author=anonymous)
    Alert.objects.filter(moderator=current).update(moderator=anonymous)
    BannedEmailProvider.objects.filter(moderator=current).update(moderator=anonymous)
    # Solved hat requests anonymization
    HatRequest.objects.filter(moderator=current).update(moderator=anonymous)
    # In case current user has been moderator in the past
    Comment.objects.filter(editor=current).update(editor=anonymous)
    for topic in PrivateTopic.objects.filter(Q(author=current) | Q(participants__in=[current])):
        if topic.one_participant_remaining():
            topic.delete()
        else:
            topic.remove_participant(current)
            topic.save()
    Topic.objects.filter(solved_by=current).update(solved_by=anonymous)
    Topic.objects.filter(author=current).update(author=anonymous)

    # Any content exclusively owned by the unregistering member will
    # be deleted just before the User object (using a pre_delete
    # receiver).
    #
    # Regarding galleries, there are two cases:
    #
    # - "personal galleries" with one owner (the unregistering
    #   user). The user's ownership is removed and replaced by an
    #   anonymous user in order not to lost the gallery.
    #
    # - "personal galleries" with many other owners. It is safe to
    #   remove the user's ownership, the gallery won't be lost.

    galleries = UserGallery.objects.filter(user=current)
    for gallery in galleries:
        if gallery.gallery.get_linked_users().count() == 1:
            anonymous_gallery = UserGallery()
            anonymous_gallery.user = external
            anonymous_gallery.mode = "w"
            anonymous_gallery.gallery = gallery.gallery
            anonymous_gallery.save()
    galleries.delete()

    # Remove API access (tokens + applications)
    for token in AccessToken.objects.filter(user=current):
        token.revoke()

    logout(request)
    User.objects.filter(pk=current.pk).delete()
    return redirect(reverse("homepage"))
Пример #21
0
def modify_gallery(request):
    """Modify gallery instance."""

    # Global actions

    if "delete_multi" in request.POST:
        l = request.POST.getlist("items")

        # Don't delete gallery when it's link to tutorial
        free_galleries = []
        for g_pk in l:
            if Tutorial.objects.filter(gallery__pk=g_pk).exists():
                gallery = Gallery.objects.get(pk=g_pk)
                messages.error(
                    request,
                    "La galerie '{}' ne peut pas être supprimée car elle est liée à un tutoriel existant"
                    .format(gallery.title))
            else:
                free_galleries.append(g_pk)

        perms = UserGallery.objects.filter(gallery__pk__in=free_galleries,
                                           user=request.user,
                                           mode="W").count()

        # Check that the user has the RW right on each gallery

        if perms < len(free_galleries):
            raise PermissionDenied

        # Delete all the permissions on all the selected galleries

        UserGallery.objects.filter(gallery__pk__in=free_galleries).delete()

        # Delete all the images of the gallery (autodelete of file)

        Image.objects.filter(gallery__pk__in=free_galleries).delete()

        # Finally delete the selected galleries

        Gallery.objects.filter(pk__in=free_galleries).delete()
        return redirect(reverse("zds.gallery.views.gallery_list"))
    elif "adduser" in request.POST:

        # Gallery-specific actions

        try:
            gal_pk = request.POST["gallery"]
        except KeyError:
            raise Http404
        gallery = get_object_or_404(Gallery, pk=gal_pk)

        # Disallow actions to read-only members

        try:
            gal_mode = UserGallery.objects.get(gallery=gallery,
                                               user=request.user)
            if gal_mode.mode != "W":
                raise PermissionDenied
        except:
            raise PermissionDenied
        form = UserGalleryForm(request.POST)
        if form.is_valid():
            user = get_object_or_404(User, username=request.POST["user"])

            # If a user is already in a user gallery, we don't add him.

            galleries = UserGallery.objects.filter(gallery=gallery,
                                                   user=user).all()
            if galleries.count() > 0:
                return redirect(gallery.get_absolute_url())
            ug = UserGallery()
            ug.user = user
            ug.gallery = gallery
            ug.mode = request.POST["mode"]
            ug.save()
        else:
            return render_template(
                "gallery/gallery/details.html", {
                    "gallery": gallery,
                    "gallery_mode": gal_mode,
                    "images": gallery.get_images(),
                    "form": form,
                })
    return redirect(gallery.get_absolute_url())