Exemplo n.º 1
0
    def view_revision(self, request, **kwargs):
        # render a page for a popup in an old revision
        revision_pk = kwargs.pop('revision_pk')
        language = request.GET.get('language')
        page_version = PageVersion.objects.get(id=revision_pk)

        # check if the current user may view the revision
        # -> if the user may see the page
        user = get_current_user()
        if not user_can_view_page(user, page_version.draft):
            messages.error(request, _('Missing permission to view this page.'))
            prev = request.META.get('HTTP_REFERER')
            if prev:
                return redirect(prev)
            else:
                raise Http404

        page_absolute_url = page_version.hidden_page.get_draft_url(
            language=language)

        context = SekizaiContext({
            'render_page': page_version.hidden_page,
            'page_version': page_version,
            'is_popup': False,
            'request': request,
            'page_absolute_url': page_absolute_url
        })

        return render(request, self.view_revision_template, context=context)
Exemplo n.º 2
0
    def get(self, request, *args, **kwargs):
        context = super(UpdateProfileView,
                        self).get_context_data(**kwargs)  # get context data

        # Add new record
        new_key = request.GET.get('new_key')
        if (new_key != None):
            if (len(new_key) > 0):
                try:
                    ssh = SSHKey(new_key)
                    ssh.parse()  # make sure the key is ok
                    key = SSHPublicKey(user=get_current_user(),
                                       comment=ssh.comment,
                                       key=new_key)
                    key.save()
                    self.key_status = 'Added new key with ID: ' + ssh.comment
                except:
                    self.key_status = 'Could not add key'

        # Updating existing record
        key_id = request.GET.get('key_id')
        update_key = request.GET.get('update_key')
        if ((update_key != None) and (key_id != None)):
            try:
                ssh = SSHKey(update_key)
                ssh.parse()  # make sure the key is ok
                key = SSHPublicKey.objects.get(id=key_id)
                key.key = update_key
                key.comment = ssh.comment
                key.save()
                self.key_status = 'Updated key with ID: ' + ssh.comment
            except:
                self.key_status = 'Could not update key'

        return super(UpdateProfileView, self).get(request, *args, **kwargs)
Exemplo n.º 3
0
def update_moderation_message(page, message):
    """This is bit special.. It updates last page state made from current user
    for given page. Its called after page is saved - page state is created when
    page gets saved (in signal), so this might have a concurrency issue, but 
    probably will work in 99,999%.
    
    If any page state isn't found in last UPDATE_TOLERANCE seconds, a new state
    will be created instead of affecting old message.    
    """

    UPDATE_TOLERANCE = 30 # max in last 30 seconds

    from cms.utils.permissions import get_current_user
    user = get_current_user()
    created = timezone.now() - datetime.timedelta(seconds=UPDATE_TOLERANCE)
    try:
        state = page.pagemoderatorstate_set.filter(user=user, created__gt=created).order_by('-created')[0]
    except IndexError:
        state = None
    if not state or state.message:
        # If no state was found or it already has a message, create a new one
        state = PageModeratorState(user=user, page=page, action=PageModeratorState.ACTION_CHANGED)

    state.message = message
    state.save()
Exemplo n.º 4
0
def post_save_user(instance, raw, created, **kwargs):
    """Signal called when new user is created, required only when CMS_PERMISSION.
    Asignes creator of the user to PageUserInfo model, so we now who had created 
    this user account.
    
    requires: CurrentUserMiddleware
    """
    from cms.utils.permissions import get_current_user
    # read current user from thread locals
    creator = get_current_user()
    if not creator or not created or not hasattr(creator, 'pk'):
        return
    from django.db import connection
    
    # i'm not sure if there is a workaround for this, somebody any ideas? What
    # we are doing here is creating PageUser on Top of existing user, i'll do it 
    # through plain SQL, its not nice, but...
    
    # TODO: find a better way than an raw sql !!
    
    cursor = connection.cursor()
    query = "INSERT INTO %s (user_ptr_id, created_by_id) VALUES (%d, %d)" % (
        PageUser._meta.db_table,
        instance.pk, 
        creator.pk
    )
    cursor.execute(query) 
    cursor.close()
Exemplo n.º 5
0
def page_changed(page, old_page=None, force_moderation_action=None):
    """Called from page post save signal. If page already had pk, old version
    of page is provided in old_page argument.
    """
    # get user from thread locals
    from cms.utils.permissions import get_current_user
    user = get_current_user()

    force_moderation_action = force_moderation_action or getattr(page, 'force_moderation_action', None)
    if force_moderation_action:
        PageModeratorState(user=user, page=page, action=force_moderation_action).save()
        return

    if not old_page:
        # just newly created page
        PageModeratorState(user=user, page=page, action=PageModeratorState.ACTION_ADD).save()

    if (old_page is None and page.published) or \
        (old_page and not old_page.published == page.published):
        action = page.published and PageModeratorState.ACTION_PUBLISH or PageModeratorState.ACTION_UNPUBLISH
        PageModeratorState(user=user, page=page, action=action).save()

    if ((old_page and not old_page.moderator_state == page.moderator_state) or not old_page) \
        and page.requires_approvement():
        # update_moderation_message can be called after this :S -> recipient will not
        # see the last message
        mail_approvement_request(page, user)
Exemplo n.º 6
0
    def create_version(cls, draft, language, version_parent=None, comment='', title=''):
        if draft.page_versions.filter(active=True, dirty=False, language=language).count() > 0:
            raise AssertionError('not dirty')

        # owner of the PageVersion is the last editor
        from cms.utils.permissions import get_current_user
        user = get_current_user()
        if user:
            try:
                owner = force_text(user)
            except AttributeError:
                # AnonymousUser may not have USERNAME_FIELD
                owner = "anonymous"
            else:
                # limit changed_by and created_by to avoid problems with Custom User Model
                if len(owner) > constants.PAGE_USERNAME_MAX_LENGTH:
                    owner = u'{0}... (id={1})'.format(owner[:constants.PAGE_USERNAME_MAX_LENGTH - 15], user.pk)
        else:
            owner = "script"

        # draft.page_versions.update(clean=False)
        hidden_page = revise_page(draft, language)
        if not version_parent and draft.page_versions.filter(language=language).exists():
            version_parent = draft.page_versions.get(active=True, language=language)

        if version_parent:
            page_version = version_parent.add_child(hidden_page=hidden_page, draft=draft, comment=comment, title=title,
                                                    active=version_parent.active, language=language, owner=owner)
            version_parent.deactivate()
        else:
            page_version = PageVersion.add_root(hidden_page=hidden_page, draft=draft, comment=comment, title=title,
                                                active=True, language=language, owner=owner)

        return page_version
Exemplo n.º 7
0
def post_save_user_group(instance, raw, created, **kwargs):
    """The same like post_save_user, but for Group, required only when 
    CMS_PERMISSION.
    Asignes creator of the group to PageUserGroupInfo model, so we now who had
    created this user account.
    
    requires: CurrentUserMiddleware
    """
    from cms.utils.permissions import get_current_user
    # read current user from thread locals
    creator = get_current_user()
    if not creator or not created:
        return
    
    from cms.models import PageUserGroup
    from django.db import connection
    
    # TODO: same as in post_save_user - raw sql is just not nice - workaround...?
    
    cursor = connection.cursor()
    query = "INSERT INTO %s (group_ptr_id, created_by_id) VALUES (%d, %d)" % (
        PageUserGroup._meta.db_table,
        instance.pk, 
        creator.pk
    )
    cursor.execute(query) 
    cursor.close()
Exemplo n.º 8
0
def page_changed(page, old_page=None, force_moderation_action=None):
    """Called from page post save signal. If page already had pk, old version
    of page is provided in old_page argument.
    """
    # get user from thread locals
    from cms.utils.permissions import get_current_user
    user = get_current_user()

    force_moderation_action = force_moderation_action or getattr(page, 'force_moderation_action', None)
    if force_moderation_action:
        PageModeratorState(user=user, page=page, action=force_moderation_action).save()
        return

    if not old_page:
        # just newly created page
        PageModeratorState(user=user, page=page, action=PageModeratorState.ACTION_ADD).save()

    if (old_page is None and page.published) or \
        (old_page and not old_page.published == page.published):
        action = page.published and PageModeratorState.ACTION_PUBLISH or PageModeratorState.ACTION_UNPUBLISH
        PageModeratorState(user=user, page=page, action=action).save()

    if ((old_page and not old_page.moderator_state == page.moderator_state) or not old_page) \
        and page.requires_approvement():
        # update_moderation_message can be called after this :S -> recipient will not
        # see the last message
        mail_approvement_request(page, user)
Exemplo n.º 9
0
def post_save_user(instance, raw, created, **kwargs):
    """Signal called when new user is created, required only when CMS_PERMISSION.
    Asignes creator of the user to PageUserInfo model, so we now who had created 
    this user account.
    
    requires: CurrentUserMiddleware
    """
    from cms.utils.permissions import get_current_user
    # read current user from thread locals
    creator = get_current_user()
    if not creator or not created or not hasattr(creator, 'pk'):
        return
    from django.db import connection

    # i'm not sure if there is a workaround for this, somebody any ideas? What
    # we are doing here is creating PageUser on Top of existing user, i'll do it
    # through plain SQL, its not nice, but...

    # TODO: find a better way than an raw sql !!

    cursor = connection.cursor()
    query = "INSERT INTO %s (user_ptr_id, created_by_id) VALUES (%d, %d)" % (
        PageUser._meta.db_table, instance.pk, creator.pk)
    cursor.execute(query)
    cursor.close()
Exemplo n.º 10
0
    def add_view(self, request, form_url='', extra_context=None):
        language = request.GET.get('language')
        draft_pk = request.GET.get('draft')

        page = get_object_or_404(Page, pk=draft_pk)

        # check if the current user may view the revision
        # -> if the user may see the page
        user = get_current_user()
        if not user_can_change_page(user, page):
            messages.error(
                request,
                _('Missing permission to edit this page which is necessary in order to create a '
                  'page version.'))
            prev = request.META.get('HTTP_REFERER')
            if prev:
                return redirect(prev)
            else:
                raise Http404

        if page.page_versions.filter(active=True,
                                     dirty=False,
                                     language=language).exists():
            messages.info(request,
                          _('This page already has a saved revision.'))
            return self.render_close_frame()

        return super(PageVersionAdmin,
                     self).add_view(request,
                                    form_url=form_url,
                                    extra_context=extra_context)
Exemplo n.º 11
0
    def save(self, commit=True):
        self.save_m2m = lambda: None
        data = self.cleaned_data

        version_id = data.get('version_id', '')
        title = data.get('title', '')
        comment = data.get('comment', '')
        draft = data['draft']
        language = data.get('language', '')

        # Detect case when editing version
        is_version_page = draft.get_root().title_set.filter(
            title__in=[BIN_ROOT_TITLE, VERSION_ROOT_TITLE]).exists()
        if not is_version_page:

            # Publish page first...
            if hasattr(self, 'publish_on_save') and self.publish_on_save:
                from cms.utils.permissions import get_current_user
                user = get_current_user()
                if isinstance(user, string_types):
                    user = User.objects.get(username=user)
                publish_page(draft, user, language)

            # Create Version second...
            return PageVersion.create_version(draft,
                                              language,
                                              version_parent=None,
                                              comment=comment,
                                              title=title,
                                              version_id=version_id)
Exemplo n.º 12
0
 def save(self, commit=True):
     """Create user, assign him to staff users, and create permissions for 
     him if required. Also assigns creator to user.
     """
     page_user = super(PageUserForm, self).save(commit=False)
     created = not page_user.created_by_id
     # assign creator to user
     if created:
         get_current_user()
         page_user.created_by = get_current_user()
     if commit:
         page_user.save()
     save_permissions(self.cleaned_data, page_user)
     if self.cleaned_data['notify_user']:
         mail_page_user_change(page_user, created, self.cleaned_data['password1'])
     return page_user
Exemplo n.º 13
0
def post_save_user_group(instance, raw, created, **kwargs):
    """The same like post_save_user, but for Group, required only when 
    CMS_PERMISSION.
    Asignes creator of the group to PageUserGroupInfo model, so we now who had
    created this user account.
    
    requires: CurrentUserMiddleware
    """
    from cms.utils.permissions import get_current_user
    # read current user from thread locals
    creator = get_current_user()
    if not creator or not created or creator.is_anonymous():
        return
    from django.db import connection
    
    # TODO: same as in post_save_user - raw sql is just not nice - workaround...?
    
    cursor = connection.cursor()
    query = "INSERT INTO %s (group_ptr_id, created_by_id) VALUES (%d, %d)" % (
        PageUserGroup._meta.db_table,
        instance.pk, 
        creator.pk
    )
    cursor.execute(query) 
    cursor.close()
Exemplo n.º 14
0
    def save(self, commit=True):
        """Create user, assign him to staff users, and create permissions for 
        him if required. Also assigns creator to user.
        """
        Super = self._password_change and PageUserForm or UserCreationForm
        user = super(Super, self).save(commit=False)

        user.is_staff = True
        created = not bool(user.pk)
        # assign creator to user
        if created:
            get_current_user()
            user.created_by = get_current_user()
        if commit:
            user.save()
        save_permissions(self.cleaned_data, user)
        if self.cleaned_data['notify_user']:
            mail_page_user_change(user, created, self.cleaned_data['password1'])
        return user
Exemplo n.º 15
0
 def save(self, commit=True):
     group = super(GenericCmsPermissionForm, self).save(commit=False)
     created = not bool(group.pk)
     # assign creator to user
     if created:
         group.created_by = get_current_user()
     if commit:
         group.save()
     save_permissions(self.cleaned_data, group)
     return group
Exemplo n.º 16
0
    def save(self, commit=True):
        """Create user, assign him to staff users, and create permissions for
        him if required. Also assigns creator to user.
        """
        Super = self._password_change and PageUserForm or UserCreationForm
        user = super(Super, self).save(commit=False)

        user.is_staff = True
        created = not bool(user.pk)
        # assign creator to user
        if created:
            get_current_user()
            user.created_by = get_current_user()
        if commit:
            user.save()
        save_permissions(self.cleaned_data, user)
        if self.cleaned_data['notify_user']:
            mail_page_user_change(user, created, self.cleaned_data['password1'])
        return user
Exemplo n.º 17
0
    def save(self, *args, **kwargs):
        from cms.utils.permissions import get_current_user
        self.changed_by = get_current_user()

        is_new_instance = not bool(self.pk)

        if is_new_instance:
            self.created_by = self.changed_by

        super(PolyCreationTrackingBaseModel, self).save(*args, **kwargs)
Exemplo n.º 18
0
 def save(self, commit=True):
     group = super(GenericCmsPermissionForm, self).save(commit=False)
     created = not bool(group.pk)
     # assign creator to user
     if created:
         group.created_by = get_current_user()
     if commit:
         group.save()
     save_permissions(self.cleaned_data, group)
     return group
Exemplo n.º 19
0
 def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
              initial=None, error_class=ErrorList, label_suffix=':',
              empty_permitted=False, instance=None):
     
     super(PagePermissionInlineAdminForm, self).__init__(data, files,
         auto_id, prefix, initial, error_class, label_suffix, empty_permitted,
         instance)
     
     user = get_current_user() # current user from threadlocals
     
     self.fields['user'].queryset = get_subordinate_users(user)
     self.fields['user'].widget.user = user # assign current user
     self.fields['group'].queryset = get_subordinate_groups(user)
Exemplo n.º 20
0
def post_save_user(instance, raw, created, **kwargs):
    """Signal called when new user is created, required only when CMS_PERMISSION.
    Assigns creator of the user to PageUserInfo model, so we know who had created
    this user account.
    
    requires: CurrentUserMiddleware
    """
    from cms.utils.permissions import get_current_user
    # read current user from thread locals
    creator = get_current_user()
    if not creator or not created or creator.is_anonymous():
        return

    page_user = PageUser(user=instance, created_by=creator)
    page_user.save()
Exemplo n.º 21
0
def post_save_user_group(instance, raw, created, **kwargs):
    """The same like post_save_user, but for Group, required only when 
    CMS_PERMISSION.
    Assigns creator of the group to PageUserGroupInfo model, so we know who had
    created this user account.
    
    requires: CurrentUserMiddleware
    """
    from cms.utils.permissions import get_current_user
    # read current user from thread locals
    creator = get_current_user()
    if not creator or not created or creator.is_anonymous():
        return
    page_user = PageUserGroup(group_ptr_id=instance.pk, created_by=creator)
    page_user.__dict__.update(instance.__dict__)
    page_user.save()
Exemplo n.º 22
0
def post_save_user(instance, raw, created, **kwargs):
    """Signal called when new user is created, required only when CMS_PERMISSION.
    Assigns creator of the user to PageUserInfo model, so we know who had created
    this user account.

    requires: CurrentUserMiddleware
    """
    from cms.utils.permissions import get_current_user
    # read current user from thread locals
    creator = get_current_user()
    if not creator or not created or creator.is_anonymous:
        return

    page_user = PageUser(user_ptr_id=instance.pk, created_by=creator)
    page_user.__dict__.update(instance.__dict__)
    page_user.save()
Exemplo n.º 23
0
    def __init__(self, *args, **kwargs):
        super(PagePermissionInlineAdminForm, self).__init__(*args, **kwargs)
        user = get_current_user() # current user from threadlocals
        site = Site.objects.get_current()
        sub_users = get_subordinate_users(user, site)

        limit_choices = True
        use_raw_id = False

        # Unfortunately, if there are > 500 users in the system, non-superusers
        # won't see any benefit here because if we ask Django to put all the
        # user PKs in limit_choices_to in the query string of the popup we're
        # in danger of causing 414 errors so we fall back to the normal input
        # widget.
        if get_cms_setting('RAW_ID_USERS'):
            if sub_users.count() < 500:
                # If there aren't too many users, proceed as normal and use a
                # raw id field with limit_choices_to
                limit_choices = True
                use_raw_id = True
            elif get_user_permission_level(user, site) == ROOT_USER_LEVEL:
                # If there are enough choices to possibly cause a 414 request
                # URI too large error, we only proceed with the raw id field if
                # the user is a superuser & thus can legitimately circumvent
                # the limit_choices_to condition.
                limit_choices = False
                use_raw_id = True

        # We don't use the fancy custom widget if the admin form wants to use a
        # raw id field for the user
        if use_raw_id:
            from django.contrib.admin.widgets import ForeignKeyRawIdWidget
            # This check will be False if the number of users in the system
            # is less than the threshold set by the RAW_ID_USERS setting.
            if isinstance(self.fields['user'].widget, ForeignKeyRawIdWidget):
                # We can't set a queryset on a raw id lookup, but we can use
                # the fact that it respects the limit_choices_to parameter.
                if limit_choices:
                    self.fields['user'].widget.rel.limit_choices_to = dict(
                        id__in=list(sub_users.values_list('pk', flat=True))
                    )
        else:
            self.fields['user'].widget = UserSelectAdminWidget()
            self.fields['user'].queryset = sub_users
            self.fields['user'].widget.user = user # assign current user

        self.fields['group'].queryset = get_subordinate_groups(user, site)
Exemplo n.º 24
0
    def revert(self, request, **kwargs):
        page_pk = kwargs.get('page_pk')
        to_version_pk = kwargs.get('version_pk')
        language = request.GET.get('language')

        page = get_object_or_404(Page, pk=page_pk)
        page_version = get_object_or_404(PageVersion, pk=to_version_pk)

        # when the page_version you want to use as target and the current page mismatch
        # -> don't know why this should happen (but we can keep it as a guard)
        if not page_version.draft == page:
            raise Http404

        # check if the current user is allowed to revert the page by checking the page publish permission
        user = get_current_user()
        if not user_can_publish_page(user, page_version.draft):
            messages.error(
                request,
                _('Missing permission to publish this page which is necessary for the rollback'
                  ))
            prev = request.META.get('HTTP_REFERER')
            if prev:
                return redirect(prev)
            else:
                raise Http404

        # Create a page_version of the page if it is dirty
        # prior to reverting
        try:
            PageVersion.create_version(page,
                                       language,
                                       version_parent=None,
                                       title='auto',
                                       comment='Auto before revert',
                                       version_id=None)
        except AssertionError as e:
            # AssertionError == page is not dirty
            pass

        revert_page(page_version, language)
        make_page_version_dirty(page, language)

        messages.info(
            request,
            _(u'You have succesfully reverted to {rev}').format(
                rev=page_version))
        return self.render_close_frame()
Exemplo n.º 25
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        user = get_current_user()  # current user from threadlocals
        site = Site.objects.get_current()
        sub_users = get_subordinate_users(user, site)

        limit_choices = True
        use_raw_id = False

        # Unfortunately, if there are > 500 users in the system, non-superusers
        # won't see any benefit here because if we ask Django to put all the
        # user PKs in limit_choices_to in the query string of the popup we're
        # in danger of causing 414 errors so we fall back to the normal input
        # widget.
        if get_cms_setting('RAW_ID_USERS'):
            if sub_users.count() < 500:
                # If there aren't too many users, proceed as normal and use a
                # raw id field with limit_choices_to
                limit_choices = True
                use_raw_id = True
            elif get_user_permission_level(user, site) == ROOT_USER_LEVEL:
                # If there are enough choices to possibly cause a 414 request
                # URI too large error, we only proceed with the raw id field if
                # the user is a superuser & thus can legitimately circumvent
                # the limit_choices_to condition.
                limit_choices = False
                use_raw_id = True

        # We don't use the fancy custom widget if the admin form wants to use a
        # raw id field for the user
        if use_raw_id:
            from django.contrib.admin.widgets import ForeignKeyRawIdWidget

            # This check will be False if the number of users in the system
            # is less than the threshold set by the RAW_ID_USERS setting.
            if isinstance(self.fields['user'].widget, ForeignKeyRawIdWidget):
                # We can't set a queryset on a raw id lookup, but we can use
                # the fact that it respects the limit_choices_to parameter.
                if limit_choices:
                    self.fields['user'].widget.rel.limit_choices_to = dict(
                        id__in=list(sub_users.values_list('pk', flat=True)))
        else:
            self.fields['user'].widget = UserSelectAdminWidget()
            self.fields['user'].queryset = sub_users
            self.fields['user'].widget.user = user  # assign current user

        self.fields['group'].queryset = get_subordinate_groups(user, site)
Exemplo n.º 26
0
def post_save_user(instance, raw, created, **kwargs):
    """Signal called when new user is created, required only when CMS_PERMISSION.
    Assigns creator of the user to PageUserInfo model, so we know who had created
    this user account.
    
    requires: CurrentUserMiddleware
    """
    from cms.utils.permissions import get_current_user
    # read current user from thread locals
    creator = get_current_user()
    if not creator or not created or not hasattr(creator, 'pk'):
        return
    from django.db import connection

    page_user = PageUser(user_ptr_id=instance.pk, created_by=creator)
    page_user.__dict__.update(instance.__dict__)
    page_user.save()
Exemplo n.º 27
0
def page_changed(page, old_page=None, force_moderation_action=None):
    """Called from page post save signal. If page already had pk, old version
    of page is provided in old_page argument.
    """
    # Only record changes on the draft version
    if not page.publisher_is_draft:
        return
    # get user from thread locals
    from cms.utils.permissions import get_current_user
    user = get_current_user()

    if force_moderation_action:
        PageModeratorState(user=user, page=page, action=force_moderation_action).save()
        page.save() # sets the page to dirty
        return

    if not old_page:
        # just newly created page
        PageModeratorState(user=user, page=page, action=PageModeratorState.ACTION_ADD).save()
Exemplo n.º 28
0
    def batch_add(self, request, **kwargs):
        # only superusers are allowed to trigger this

        user = get_current_user()
        if not user.is_superuser:
            messages.error(
                request,
                _('Only superusers are allowed to use the batch page revision creation mode'
                  ))
        else:
            num = revise_all_pages()
            messages.info(
                request,
                _(u'{num} unversioned pages have been versioned.').format(
                    num=num))

        pk = kwargs.get('pk')
        language = request.GET.get('language')
        page = Page.objects.get(pk=pk)
        return redirect(page.get_absolute_url(language), permanent=True)
Exemplo n.º 29
0
    def __init__(self,
                 data=None,
                 files=None,
                 auto_id='id_%s',
                 prefix=None,
                 initial=None,
                 error_class=ErrorList,
                 label_suffix=':',
                 empty_permitted=False,
                 instance=None):

        super(PagePermissionInlineAdminForm,
              self).__init__(data, files, auto_id, prefix, initial,
                             error_class, label_suffix, empty_permitted,
                             instance)

        user = get_current_user()  # current user from threadlocals

        self.fields['user'].queryset = get_subordinate_users(user)
        self.fields['user'].widget.user = user  # assign current user
        self.fields['group'].queryset = get_subordinate_groups(user)
Exemplo n.º 30
0
    def save(self, no_signals=False, commit=True, **kwargs):
        '''
        Args:
            commit: True if model should be really saved
        '''
        # delete template cache
        if hasattr(self, '_template_cache'):
            delattr(self, '_template_cache')

        created = not bool(self.pk)

        from cms.utils.permissions import get_current_user

        user = get_current_user()

        if user:
            try:
                changed_by = force_text(user)
            except AttributeError:
                # AnonymousUser may not have USERNAME_FIELD
                changed_by = 'anonymous'
            else:
                # limit changed_by and created_by to avoid problems with Custom User Model
                if len(changed_by) > constants.PAGE_USERNAME_MAX_LENGTH:
                    changed_by = '{0}... (id={1})'.format(
                        changed_by[:constants.PAGE_USERNAME_MAX_LENGTH - 15],
                        user.pk,
                    )

            self.changed_by = changed_by

        else:
            self.changed_by = 'script'
        if created:
            self.created_by = self.changed_by

        self.order_date = self.publication_date or self.creation_date

        if commit:
            super(Article, self).save(**kwargs)
Exemplo n.º 31
0
    def save(self, no_signals=False, commit=True, **kwargs):
        '''
        Args:
            commit: True if model should be really saved
        '''
        # delete template cache
        if hasattr(self, '_template_cache'):
            delattr(self, '_template_cache')

        created = not bool(self.pk)

        from cms.utils.permissions import get_current_user

        user = get_current_user()

        if user:
            try:
                changed_by = force_text(user)
            except AttributeError:
                # AnonymousUser may not have USERNAME_FIELD
                changed_by = 'anonymous'
            else:
                # limit changed_by and created_by to avoid problems with Custom User Model
                if len(changed_by) > constants.PAGE_USERNAME_MAX_LENGTH:
                    changed_by = u'{0}... (id={1})'.format(
                        changed_by[:constants.PAGE_USERNAME_MAX_LENGTH - 15],
                        user.pk,
                    )

            self.changed_by = changed_by

        else:
            self.changed_by = 'script'
        if created:
            self.created_by = self.changed_by

        self.order_date = self.publication_date or self.creation_date

        if commit:
            super(Article, self).save(**kwargs)
Exemplo n.º 32
0
def update_moderation_message(page, message):
    """This is bit special.. It updates last page state made from current user
    for given page. Its called after page is saved - page state is created when
    page gets saved (in signal), so this might have a concurrency issue, but 
    probably will work in 99,999%.
    
    If any page state is'nt found in last UPDATE_TOLERANCE seconds, a new state
    will be created instead of affecting old message.    
    """
    
    UPDATE_TOLERANCE = 30 # max in last 30 seconds
    
    user = get_current_user()
    created = datetime.datetime.now() - datetime.timedelta(seconds=UPDATE_TOLERANCE)
    try:
        state = page.pagemoderatorstate_set.filter(user=user, created__gt=created).order_by('-created')[0]
        # just state without message!!
        assert not state.message  
    except (IndexError, AssertionError):
        state = PageModeratorState(user=user, page=page, action=PageModeratorState.ACTION_CHANGED)
    
    state.message = message
    state.save()
Exemplo n.º 33
0
    def save(self, commit=True):
        """Create user, assign him to staff users, and create permissions for 
        him if required. Also assigns creator to user.
        """
        Super = self._password_change and PageUserForm or UserCreationForm  
        user = super(Super, self).save(commit=False)
        
        user.is_staff = True
        created = not bool(user.pk)
        # assign creator to user
        if created:
            user.created_by = get_current_user()

        if commit:
            user.save()

        models = ((Page, 'page'), (PageUser, 'pageuser'), (Group, 'pageuser'), (PagePermission, 'pagepermission'))
        for model, name in models:
            content_type = ContentType.objects.get_for_model(model)
            for t in ('add', 'change', 'delete'):
                if not user.pk:
                    # save user, otherwise we can't assign permissions to him
                    user.save()
                
                # add permission `t` to model `model`
                codename = getattr(model._meta, 'get_%s_permission' % t)()
                permission = Permission.objects.get(content_type=content_type, codename=codename)
                
                if self.cleaned_data.get('can_%s_%s' % (t, name), None):
                    user.user_permissions.add(permission)
                else:
                    user.user_permissions.remove(permission)

        if self.cleaned_data['notify_user']:
            mail_page_user_change(user, created, self.cleaned_data['password1'])
        
        return user
Exemplo n.º 34
0
 def __init__(self, *args, **kwargs):
     site_url = get_current_site(self)
     self.user = get_current_user()
     self.new_project_url = str(site_url) + '/' + str(self.user) + '/'
     super(ChipDesignAdd, self).__init__(*args, **kwargs)
Exemplo n.º 35
0
    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        # ToDo: make current user customizeable
        self.created_by = get_current_user()

        return super(Ticket, self).save(force_insert, force_update, using, update_fields)
Exemplo n.º 36
0
    def diff_view(self, request, **kwargs):
        # view that shows a revision on the left and one on the right
        # if the right revision has value zero: the current page is used!
        # -> page id is only necessary in the utter case
        # if the comparison_pk is zero: the latest version is used
        # comparison_pk and base_pk are primary keys for *pages*!

        # also called left_pk
        left_pk = kwargs.pop('left_pk')
        # also called right_pk
        right_pk = kwargs.pop('right_pk')
        page_pk = kwargs.pop('page_pk')

        right_page_is_active_page = True

        language = request.GET.get('language')

        left = 'page'
        right = 'page'

        # get the draft we are talking about
        page_draft = get_object_or_404(Page, pk=page_pk).get_draft_object()

        # check if the current user may view the revision
        # -> if the user may see the page
        user = get_current_user()
        if not user_can_view_page(user, page_draft):
            messages.error(request, _('Missing permission to view this page.'))
            prev = request.META.get('HTTP_REFERER')
            if prev:
                return redirect(prev)
            else:
                raise Http404

        # the right panel has id=0
        # -> use the draft of the page
        # -> else: fetch the page
        if int(right_pk) == 0:
            right_page = page_draft
            right_page_is_active_page = True
        else:
            right = 'pageVersion'
            right_page = PageVersion.objects.get(pk=right_pk)
            right_page_is_active_page = False

        # the left panel has id=0
        # -> use the latest PageVersion draft of the page
        # -> else: fetch the page
        if int(left_pk) == 0:
            page_draft_versions = PageVersion.objects.filter(draft=page_draft, active=True, language=language)\
                .order_by('-hidden_page__changed_date')[:1]

            if page_draft_versions.count() > 0:
                left_page = page_draft_versions.first()
                left = 'pageVersion'
            else:
                messages.info(request,
                              _(u'There are no snapshots for this page'))
                return self.render_close_frame()
        else:
            left = 'pageVersion'
            left_page = PageVersion.objects.get(pk=left_pk)

        # list of page's revisions to show as the left sidebar
        revision_list = PageVersion.objects.filter(draft=page_draft,
                                                   language=language)
        # group the revisions by date
        grouped_revisions = {}
        for rev in revision_list.iterator():
            key = rev.hidden_page.changed_date.strftime("%Y-%m-%d")
            if key not in grouped_revisions.keys():
                grouped_revisions[key] = []
            grouped_revisions[key].insert(0, rev)
        sorted_grouped_revisions = sorted(grouped_revisions.items(),
                                          key=lambda i: i[0],
                                          reverse=True)

        # differences between the placeholders
        if left == 'pageVersion':
            l_page = left_page.hidden_page
        else:
            l_page = left_page
        if right == 'pageVersion':
            r_page = right_page.hidden_page
        else:
            r_page = right_page

        diffs = create_placeholder_contents(l_page, r_page, request, language)

        left_page_absolute_url = left_page.hidden_page.get_draft_url(
            language=language)

        context = SekizaiContext({
            'left':
            left,
            'right':
            right,
            'left_page':
            left_page,
            'right_page':
            right_page,
            'is_popup':
            True,
            'page':
            page_draft.pk,
            'active_left_page_version_pk':
            left_page.pk,
            'request':
            request,
            'sorted_grouped_revisions':
            sorted_grouped_revisions,
            'active_language':
            language,
            'all_languages':
            page_draft.languages.split(','),
            'diffs':
            diffs,
            'left_page_absolute_url':
            left_page_absolute_url,
            'right_page_is_active_page':
            right_page_is_active_page
        })

        return render(request,
                      self.diff_view_template,
                      context=context.flatten())
Exemplo n.º 37
0
    def create_version(cls,
                       draft,
                       language,
                       version_parent=None,
                       comment='',
                       title='',
                       version_id=None):
        if draft.page_versions.filter(
                active=True, dirty=False, language=language).count() > 0:
            raise AssertionError('not dirty')

        # Check that title is included if required -
        if not title and not ALLOW_BLANK_TITLE:
            raise AssertionError('Version Title cannot be blank')

        # owner of the PageVersion is the last editor
        from cms.utils.permissions import get_current_user
        user = get_current_user()
        if user:
            try:
                owner = force_text(user)
            except AttributeError:
                # AnonymousUser may not have USERNAME_FIELD
                owner = "anonymous"
            else:
                # limit changed_by and created_by to avoid problems with Custom User Model
                if len(owner) > constants.PAGE_USERNAME_MAX_LENGTH:
                    owner = u'{0}... (id={1})'.format(
                        owner[:constants.PAGE_USERNAME_MAX_LENGTH - 15],
                        user.pk)
        else:
            owner = "script"

        if isinstance(user, string_types):
            from cms.models import User
            user = User.objects.get(username=user)

        hidden_page = revise_page(draft, language, user, version_id)

        if not version_parent and draft.page_versions.filter(
                language=language).exists():
            version_parent = draft.page_versions.get(active=True,
                                                     language=language)

        if version_parent:
            page_version = version_parent.add_child(
                hidden_page=hidden_page,
                draft=draft,
                comment=comment,
                title=title,
                version_id=version_id,
                active=version_parent.active,
                language=language,
                owner=owner)
            version_parent.deactivate()
        else:
            page_version = PageVersion.add_root(hidden_page=hidden_page,
                                                draft=draft,
                                                comment=comment,
                                                title=title,
                                                version_id=version_id,
                                                active=True,
                                                language=language,
                                                owner=owner)

        return page_version
Exemplo n.º 38
0
 def save(self, commit=True):
     self.instance._set_default_author(get_current_user())
     return super(PostWizardForm, self).save(commit)
Exemplo n.º 39
0
 def __init__(self, *args, **kwargs):
     super(PagePermissionInlineAdminForm, self).__init__(*args, **kwargs)
     user = get_current_user() # current user from threadlocals
     self.fields['user'].queryset = get_subordinate_users(user)
     self.fields['user'].widget.user = user # assign current user
     self.fields['group'].queryset = get_subordinate_groups(user)
Exemplo n.º 40
0
 def __init__(self, *args, **kwargs):
     user = get_current_user()
     self.success_url = reverse_lazy('profile', args=[user.id])
     super(SSHKeyDelete, self).__init__(*args, **kwargs)
Exemplo n.º 41
0
 def save(self, commit=True):
     self.instance._set_default_author(get_current_user())
     instance = super().save(commit)
     self.add_plugin()
     return instance
Exemplo n.º 42
0
 def save(self, commit=True):
     self.instance._set_default_author(get_current_user())
     return super(PostWizardForm, self).save(commit)