示例#1
0
 def has_copy_plugin_permission(self, request, source_placeholder, target_placeholder, plugins):
     if not source_placeholder.has_add_permission(request) or not target_placeholder.has_add_permission(request):
         return False
     for plugin in plugins:
         if not permissions.has_plugin_permission(request.user, plugin.plugin_type, "add"):
             return False
     return True
示例#2
0
    def add_plugin(self, request):
        # only allow POST
        if request.method != "POST":
            raise Http404
        plugin_type = request.POST['plugin_type']
        if not has_plugin_permission(request.user, plugin_type, "add"):
            return HttpResponseForbidden("You don't have permission to add plugins")

        placeholder_id = request.POST.get('placeholder', None)
        position = None
        language = self.get_language_from_request(request)
        parent = None
        # check if we got a placeholder (id)
        if placeholder_id:
            placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
        else: # else get the parent_id
            parent_id = request.POST.get('parent_id', None)
            if not parent_id: # if we get neither a placeholder nor a parent, bail out
                raise Http404
            parent = get_object_or_404(CMSPlugin, pk=parent_id)
            placeholder = parent.placeholder

        # check add permissions on placeholder
        if not placeholder.has_add_permission(request):
            return HttpResponseForbidden(_("You don't have permission to add content here."))

        try:
            has_reached_plugin_limit(placeholder, plugin_type, language)
        except PluginLimitReached, e:
            return HttpResponseBadRequest(str(e))
示例#3
0
    def save(self, commit=True):
        question = super(CreateFaqQuestionForm, self).save(commit=False)

        # If 'content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        answer = self.cleaned_data.get('answer', '')
        content_plugin = get_cms_setting('WIZARD_CONTENT_PLUGIN')
        if answer and permissions.has_plugin_permission(
                self.user, content_plugin, 'add'):

            # If the question has not been saved, then there will be no
            # Placeholder set-up for this question yet, so, ensure we have saved
            # first.
            if not question.pk:
                question.save()

            if question and question.answer:
                plugin_kwarg = {
                    'placeholder': question.answer,
                    'plugin_type': content_plugin,
                    'language': self.language_code,
                    get_cms_setting('WIZARD_CONTENT_PLUGIN_BODY'): answer,
                }
                add_plugin(**plugin_kwarg)

        if commit:
            question.save()

        return question
示例#4
0
 def can_detach(cls, user, target_placeholder, plugins):
     return all(
         has_plugin_permission(
             user,
             plugin.plugin_type,
             'add',
         ) for plugin in plugins) and target_placeholder.check_source(user)
示例#5
0
 def has_move_plugin_permission(self, request, plugin, target_placeholder):
     if not permissions.has_plugin_permission(request.user,
                                              plugin.plugin_type, "change"):
         return False
     if not target_placeholder.has_change_permission(request):
         return False
     return True
示例#6
0
    def has_add_plugin_permission(self, user, plugin_type):
        if not permissions.has_plugin_permission(user, plugin_type, "add"):
            return False

        if not self.has_change_permission(user):
            return False
        return True
示例#7
0
    def save(self, commit=True):
        article = super(CreateNewsBlogArticleForm, self).save(commit=False)

        # Set owner to current user
        article.owner = self.user

        # If 'content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        content = clean_html(self.cleaned_data.get('content', ''), False)
        if content and permissions.has_plugin_permission(
                self.user, 'TextPlugin', 'add'):

            # If the article has not been saved, then there will be no
            # Placeholder set-up for this article yet, so, ensure we have saved
            # first.
            if not article.pk:
                article.save()

            if article and article.content:
                add_plugin(
                    placeholder=article.content,
                    plugin_type='TextPlugin',
                    language=self.language_code,
                    body=content,
                )

        with transaction.atomic():
            with create_revision():
                article.save()
                if self.user:
                    set_user(self.user)
                set_comment(ugettext("Initial version."))

        return article
示例#8
0
    def has_add_plugin_permission(self, user, plugin_type):
        if not permissions.has_plugin_permission(user, plugin_type, "add"):
            return False

        if not self.has_change_permission(user):
            return False
        return True
示例#9
0
    def save(self, commit=True):

        post = super(PostCreationForm, self).save(commit=False)
        # Set owner to current user
        post.author = self.user

        # If 'content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        content = self.cleaned_data.get('content', '')
        if content and permissions.has_plugin_permission(
                self.user, 'TextPlugin', 'add'):

            # If the post has not been saved, then there will be no
            # Placeholder set-up for this article yet, so, ensure we have saved
            # first.
            if not post.pk:
                post.save()

            if post and post.content:
                add_plugin(
                    placeholder=post.content,
                    plugin_type='TextPlugin',
                    language=self.language_code,
                    body=content,
                )

        if commit:
            post.save()

        return post
示例#10
0
    def save(self, commit=True):

        post = super(PostCreationForm, self).save(commit=False)
        # Set owner to current user
        post.author = self.user

        # If 'content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        content = self.cleaned_data.get('content', '')
        if content and permissions.has_plugin_permission(
                self.user, 'TextPlugin', 'add'):

            # If the post has not been saved, then there will be no
            # Placeholder set-up for this article yet, so, ensure we have saved
            # first.
            if not post.pk:
                post.save()

            if post and post.content:
                add_plugin(
                    placeholder=post.content,
                    plugin_type='TextPlugin',
                    language=self.language_code,
                    body=content,
                )

        if commit:
            post.save()

        return post
示例#11
0
 def has_add_plugin_permission(self, request, placeholder, plugin_type):
     if not permissions.has_plugin_permission(request.user, plugin_type,
                                              "add"):
         return False
     if not placeholder.has_add_permission(request):
         return False
     return True
示例#12
0
    def add_plugin(self, request):
        # only allow POST
        if request.method != "POST":
            raise Http404
        plugin_type = request.POST['plugin_type']
        if not has_plugin_permission(request.user, plugin_type, "add"):
            return HttpResponseForbidden(
                "You don't have permission to add plugins")

        placeholder_id = request.POST.get('placeholder', None)
        position = None
        language = get_language_from_request(request)
        parent = None
        # check if we got a placeholder (id)
        if placeholder_id:
            placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
        else:  # else get the parent_id
            parent_id = request.POST.get('parent_id', None)
            if not parent_id:  # if we get neither a placeholder nor a parent, bail out
                raise Http404
            parent = get_object_or_404(CMSPlugin, pk=parent_id)
            placeholder = parent.placeholder

        # check add permissions on placeholder
        if not placeholder.has_add_permission(request):
            return HttpResponseForbidden(
                _("You don't have permission to add content here."))

        # check the limits defined in CMS_PLACEHOLDER_CONF for this placeholder
        limits = settings.CMS_PLACEHOLDER_CONF.get(placeholder.slot,
                                                   {}).get('limits', None)
        if limits:
            count = placeholder.cmsplugin_set.count()
            global_limit = limits.get("global", None)
            type_limit = limits.get(plugin_type, None)
            # check the global limit first
            if global_limit and count >= global_limit:
                return HttpResponseBadRequest(
                    "This placeholder already has the maximum number of plugins."
                )
            elif type_limit:  # then check the type specific limit
                type_count = CMSPlugin.objects.filter(
                    language=language,
                    placeholder=placeholder,
                    plugin_type=plugin_type).count()
                if type_count >= type_limit:
                    return HttpResponseBadRequest(
                        "This placeholder already has the maximum number (%s) "
                        "of %s plugins." % (type_limit, plugin_type))

        # actually add the plugin
        plugin = CMSPlugin(language=language,
                           plugin_type=plugin_type,
                           position=position,
                           placeholder=placeholder,
                           parent=parent)
        plugin.save()

        # returns it's ID as response
        return HttpResponse(str(plugin.pk))
示例#13
0
    def save(self, commit=True):
        article = super(CreateNewsBlogArticleForm, self).save(commit=False)

        # Set owner to current user
        article.owner = self.user

        # If 'content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        content = clean_html(self.cleaned_data.get('content', ''), False)
        if content and permissions.has_plugin_permission(
                self.user, 'TextPlugin', 'add'):

            # If the article has not been saved, then there will be no
            # Placeholder set-up for this article yet, so, ensure we have saved
            # first.
            if not article.pk:
                article.save()

            if article and article.content:
                add_plugin(
                    placeholder=article.content,
                    plugin_type='TextPlugin',
                    language=self.language_code,
                    body=content,
                )

        with transaction.atomic():
            with create_revision():
                article.save()
                if self.user:
                    set_user(self.user)
                set_comment(ugettext("Initial version."))

        return article
示例#14
0
 def has_delete_plugin_permission(self, request, plugin):
     if not permissions.has_plugin_permission(request.user, plugin.plugin_type, "delete"):
         return False
     placeholder = plugin.placeholder
     if not placeholder.has_delete_permission(request):
         return False
     return True
示例#15
0
    def save(self, commit=True):
        event = super(CreateEventForm, self).save(commit=False)

        # If 'content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        description = self.cleaned_data.get('description', '')
        content_plugin = get_cms_setting('WIZARD_CONTENT_PLUGIN')
        if description and permissions.has_plugin_permission(
                self.user, content_plugin, 'add'):

            # If the event has not been saved, then there will be no
            # Placeholder set-up for this event yet, so, ensure we have saved
            # first.
            if not event.pk:
                event.save()

            if event and event.description:
                # we have to use kwargs because we don't know in advance what
                # is the 'body' field for configured plugin
                plugin_kwargs = {
                    'placeholder': event.description,
                    'plugin_type': content_plugin,
                    'language': self.language_code,
                    get_cms_setting('WIZARD_CONTENT_PLUGIN_BODY'): description,
                }
                add_plugin(**plugin_kwargs)

        if commit:
            event.save()

        return event
示例#16
0
    def save(self, commit=True):
        job_opening = super(CreateJobOpeningForm, self).save(commit=False)

        # If 'content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        content = clean_html(self.cleaned_data.get('content', ''), False)
        content_plugin = get_cms_setting('WIZARD_CONTENT_PLUGIN')
        if content and permissions.has_plugin_permission(
                self.user, 'TextPlugin', 'add'):

            # If the job_opening has not been saved, then there will be no
            # Placeholder set-up for this question yet, so, ensure we have saved
            # first.
            if not job_opening.pk:
                job_opening.save()

            if job_opening and job_opening.content:
                plugin_kwargs = {
                    'placeholder': job_opening.content,
                    'plugin_type': content_plugin,
                    'language': self.language_code,
                    get_cms_setting('WIZARD_CONTENT_PLUGIN_BODY'): content,
                }
                add_plugin(**plugin_kwargs)

        with transaction.atomic():
            with revision_context_manager.create_revision():
                job_opening.save()
                if self.user:
                    revision_context_manager.set_user(self.user)
                revision_context_manager.set_comment(
                    ugettext("Initial version."))

        return job_opening
示例#17
0
 def has_delete_plugin_permission(self, request, plugin):
     if not permissions.has_plugin_permission(request.user, plugin.plugin_type, "delete"):
         return False
     placeholder = plugin.placeholder
     if not placeholder.has_delete_permission(request):
         return False
     return True
    def has_delete_plugin_permission(self, user, plugin):
        if not permissions.has_plugin_permission(user, plugin.plugin_type, "delete"):
            return False

        if not self.has_change_permission(user):
            return False
        return True
示例#19
0
    def save(self, commit=True):
        job_opening = super(CreateJobOpeningForm, self).save(commit=False)

        # If 'job_opening_content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        job_opening_content = clean_html(self.cleaned_data.get('job_opening_content', ''), False)

        content_plugin = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN')
        content_field = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN_BODY')

        if job_opening_content and permissions.has_plugin_permission(
                self.user, content_plugin, 'add'):

            # If the job_opening has not been saved, then there will be no
            # Placeholder set-up for this question yet, so, ensure we have saved
            # first.
            if not job_opening.pk:
                job_opening.save()

            if job_opening and job_opening.content:
                plugin_kwargs = {
                    'placeholder': job_opening.content,
                    'plugin_type': content_plugin,
                    'language': self.language_code,
                    content_field: job_opening_content,
                }
                add_plugin(**plugin_kwargs)

        job_opening.save()

        return job_opening
示例#20
0
    def add_plugin(self, request):
        # only allow POST
        if request.method != "POST":
            raise Http404
        plugin_type = request.POST['plugin_type']
        if not has_plugin_permission(request.user, plugin_type, "add"):
            return HttpResponseForbidden(
                "You don't have permission to add plugins")

        placeholder_id = request.POST.get('placeholder', None)
        position = None
        language = self.get_language_from_request(request)
        parent = None
        # check if we got a placeholder (id)
        if placeholder_id:
            placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
        else:  # else get the parent_id
            parent_id = request.POST.get('parent_id', None)
            if not parent_id:  # if we get neither a placeholder nor a parent, bail out
                raise Http404
            parent = get_object_or_404(CMSPlugin, pk=parent_id)
            placeholder = parent.placeholder

        # check add permissions on placeholder
        if not placeholder.has_add_permission(request):
            return HttpResponseForbidden(
                _("You don't have permission to add content here."))

        try:
            has_reached_plugin_limit(placeholder, plugin_type, language)
        except PluginLimitReached, e:
            return HttpResponseBadRequest(str(e))
示例#21
0
def create_default_plugins(request, placeholders, template, lang):
    """
    Create all default plugins for the given ``placeholders`` if they have
    a "default_plugins" configuration value in settings.
    return all plugins, children, grandchildren (etc.) created
    """
    from cms.api import add_plugin
    plugins = list()
    for placeholder in placeholders:
        default_plugins = get_placeholder_conf("default_plugins",
                                               placeholder.slot, template,
                                               None)
        if not default_plugins:
            continue
        if not placeholder.has_add_permission(request):
            continue
        for conf in default_plugins:
            if not permissions.has_plugin_permission(
                    request.user, conf['plugin_type'], "add"):
                continue
            plugin = add_plugin(placeholder, conf['plugin_type'], lang,
                                **conf['values'])
            plugins.append(plugin)
            if 'children' in conf:
                children = create_default_children_plugins(
                    request, placeholder, lang, plugin, conf['children'])
                plugins += children
            plugin.notify_on_autoadd(request, conf)
    return plugins
示例#22
0
def create_default_children_plugins(request, placeholder, lang, parent_plugin,
                                    children_conf):
    """
    Create all default children plugins in the given ``placeholder``.
    If a child have children, this function recurse.
    Return all children and grandchildren (etc.) created
    """
    from cms.api import add_plugin
    children = list()
    grandchildren = list()
    for conf in children_conf:
        if not permissions.has_plugin_permission(request.user,
                                                 conf['plugin_type'], "add"):
            continue
        plugin = add_plugin(placeholder, conf['plugin_type'], lang,
                            **conf['values'])
        plugin.parent = parent_plugin
        plugin.save()
        if 'children' in conf:
            grandchildren += create_default_children_plugins(
                request, placeholder, lang, plugin, conf['children'])
        plugin.notify_on_autoadd(request, conf)
        children.append(plugin)
    parent_plugin.notify_on_autoadd_children(request, conf, children)
    return children + grandchildren
示例#23
0
 def has_copy_plugin_permission(self, request, source_placeholder, target_placeholder, plugins):
     if not source_placeholder.has_add_permission(request) or not target_placeholder.has_add_permission(
             request):
         return False
     for plugin in plugins:
         if not permissions.has_plugin_permission(request.user, plugin.plugin_type, "add"):
             return False
     return True
示例#24
0
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')

        super().__init__(*args, **kwargs)

        if not has_plugin_permission(self.user, 'Alias', 'add'):
            self.fields['replace'].widget = forms.HiddenInput()

        self.set_category_widget(self.user)
示例#25
0
    def add_plugin(self, request):
        # only allow POST
        if request.method != "POST":
            raise Http404
        plugin_type = request.POST['plugin_type']
        if not has_plugin_permission(request.user, plugin_type, "add"):
            return HttpResponseForbidden("You don't have permission to add plugins")

        placeholder_id = request.POST.get('placeholder', None)
        position = None
        language = get_language_from_request(request)
        parent = None
        # check if we got a placeholder (id)
        if placeholder_id:
            placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
        else: # else get the parent_id
            parent_id = request.POST.get('parent_id', None)
            if not parent_id: # if we get neither a placeholder nor a parent, bail out
                raise Http404
            parent = get_object_or_404(CMSPlugin, pk=parent_id)
            placeholder = parent.placeholder
        
        # check add permissions on placeholder
        if not placeholder.has_add_permission(request):
            return HttpResponseForbidden(_("You don't have permission to add content here."))
        
        # check the limits defined in CMS_PLACEHOLDER_CONF for this placeholder
        limits = settings.CMS_PLACEHOLDER_CONF.get(placeholder.slot, {}).get('limits', None)
        if limits:
            count = placeholder.cmsplugin_set.count()
            global_limit = limits.get("global", None)
            type_limit = limits.get(plugin_type, None)
            # check the global limit first
            if global_limit and count >= global_limit:
                return HttpResponseBadRequest(
                    "This placeholder already has the maximum number of plugins."
                )
            elif type_limit: # then check the type specific limit
                type_count = CMSPlugin.objects.filter(
                    language=language, placeholder=placeholder, plugin_type=plugin_type
                ).count()
                if type_count >= type_limit:
                    return HttpResponseBadRequest(
                        "This placeholder already has the maximum number (%s) "
                        "of %s plugins." % (type_limit, plugin_type)
                    )

        # position plugin at the end of the list
        position = CMSPlugin.objects.filter(placeholder=placeholder).count()

        # actually add the plugin
        plugin = CMSPlugin(language=language, plugin_type=plugin_type,
            position=position, placeholder=placeholder, parent=parent) 
        plugin.save()
        
        # returns it's ID as response
        return HttpResponse(str(plugin.pk))
    def has_move_plugin_permission(self, user, plugin, target_placeholder):
        if not permissions.has_plugin_permission(user, plugin.plugin_type, "change"):
            return False

        if not target_placeholder.has_change_permission(user):
            return False

        if self != target_placeholder and not self.has_change_permission(user):
            return False
        return True
示例#27
0
    def can_create_alias(cls, user, plugins=None, replace=False):
        if not user.has_perm(get_model_permission_codename(AliasModel,
                                                           'add'), ):
            return False

        if not plugins:
            return True
        elif replace:
            target_placeholder = plugins[0].placeholder
            if (not target_placeholder.check_source(user)
                    or not has_plugin_permission(user, Alias.__name__, 'add')):
                return False

        return all(
            has_plugin_permission(
                user,
                plugin.plugin_type,
                'add',
            ) for plugin in plugins)
示例#28
0
    def save(self, commit=True):
        event = super(CreateEventForm, self).save(commit=False)

        if not commit:
            return event

        # If 'content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        description = clean_html(
            self.cleaned_data.get('description', ''), False)

        try:
            # CMS >= 3.3.x
            content_plugin = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN')
        except KeyError:
            # CMS <= 3.2.x
            content_plugin = get_cms_setting('WIZARD_CONTENT_PLUGIN')

        try:
            # CMS >= 3.3.x
            content_field = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN_BODY')
        except KeyError:
            # CMS <= 3.2.x
            content_field = get_cms_setting('WIZARD_CONTENT_PLUGIN_BODY')

        if description and permissions.has_plugin_permission(
                self.user, content_plugin, 'add'):
            # If the event has not been saved, then there will be no
            # Placeholder set-up for this event yet, so, ensure we have saved
            # first.
            if not event.pk:
                event.save()

            if event and event.description:
                # we have to use kwargs because we don't know in advance what
                # is the 'body' field for configured plugin
                plugin_kwargs = {
                    'placeholder': event.description,
                    'plugin_type': content_plugin,
                    'language': self.language_code,
                    content_field: description,
                }
                add_plugin(**plugin_kwargs)

        with transaction.atomic():
            with revision_context_manager.create_revision():
                event.save()

                if self.user:
                    revision_context_manager.set_user(self.user)
                revision_context_manager.set_comment(
                    ugettext("Initial version."))
        return event
示例#29
0
    def save(self, commit=True):
        event = super(CreateEventForm, self).save(commit=False)

        if not commit:
            return event

        # If 'content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        description = clean_html(self.cleaned_data.get('description', ''),
                                 False)

        try:
            # CMS >= 3.3.x
            content_plugin = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN')
        except KeyError:
            # CMS <= 3.2.x
            content_plugin = get_cms_setting('WIZARD_CONTENT_PLUGIN')

        try:
            # CMS >= 3.3.x
            content_field = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN_BODY')
        except KeyError:
            # CMS <= 3.2.x
            content_field = get_cms_setting('WIZARD_CONTENT_PLUGIN_BODY')

        if description and permissions.has_plugin_permission(
                self.user, content_plugin, 'add'):
            # If the event has not been saved, then there will be no
            # Placeholder set-up for this event yet, so, ensure we have saved
            # first.
            if not event.pk:
                event.save()

            if event and event.description:
                # we have to use kwargs because we don't know in advance what
                # is the 'body' field for configured plugin
                plugin_kwargs = {
                    'placeholder': event.description,
                    'plugin_type': content_plugin,
                    'language': self.language_code,
                    content_field: description,
                }
                add_plugin(**plugin_kwargs)

        with transaction.atomic():
            with revision_context_manager.create_revision():
                event.save()

                if self.user:
                    revision_context_manager.set_user(self.user)
                revision_context_manager.set_comment(
                    ugettext("Initial version."))
        return event
示例#30
0
    def edit_plugin(self, request, plugin_id):
        plugin_id = int(plugin_id)
        # get the plugin to edit of bail out
        cms_plugin = get_object_or_404(CMSPlugin, pk=plugin_id)

        if not has_plugin_permission(request.user, cms_plugin.plugin_type, "change"):
            return HttpResponseForbidden(_("You don't have permission to add plugins"))

        # check that the user has permission to change this plugin
        if not cms_plugin.placeholder.has_change_permission(request):
            return HttpResponseForbidden(_("You don't have permission to add content here."))
        
        instance, plugin_admin = cms_plugin.get_plugin_instance(self.admin_site)
        
        plugin_admin.cms_plugin_instance = cms_plugin
        plugin_admin.placeholder = cms_plugin.placeholder
        
        if request.method == "POST":
            # set the continue flag, otherwise will plugin_admin make redirect to list
            # view, which actually does'nt exists
            post_request = request.POST.copy()
            post_request['_continue'] = True
            request.POST = post_request
        
        if not instance:
            # instance doesn't exist, call add view
            response = plugin_admin.add_view(request)
     
        else:
            # already saved before, call change view
            # we actually have the instance here, but since i won't override
            # change_view method, is better if it will be loaded again, so
            # just pass id to plugin_admin
            response = plugin_admin.change_view(request, str(plugin_id))
        
        if request.method == "POST" and plugin_admin.object_successfully_changed:
            # read the saved object from plugin_admin - ugly but works
            saved_object = plugin_admin.saved_object
            
            context = {
                'CMS_MEDIA_URL': settings.CMS_MEDIA_URL, 
                'plugin': saved_object, 
                'is_popup': True, 
                'name': unicode(saved_object), 
                "type": saved_object.get_plugin_name(),
                'plugin_id': plugin_id,
                'icon': force_escape(escapejs(saved_object.get_instance_icon_src())),
                'alt': force_escape(escapejs(saved_object.get_instance_icon_alt())),
            }
            return render_to_response('admin/cms/page/plugin_forms_ok.html', context, RequestContext(request))
            
        return response
示例#31
0
    def save(self, commit=True):
        question = super(CreateFaqQuestionForm, self).save(commit=False)

        # If 'content' field has value, create a TextPlugin with same and add
        # it to the PlaceholderField
        answer = clean_html(self.cleaned_data.get('answer', ''), False)

        try:
            # CMS >= 3.3.x
            content_plugin = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN')
        except KeyError:
            # CMS <= 3.2.x
            content_plugin = get_cms_setting('WIZARD_CONTENT_PLUGIN')

        try:
            # CMS >= 3.3.x
            content_field = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN_BODY')
        except KeyError:
            # CMS <= 3.2.x
            content_field = get_cms_setting('WIZARD_CONTENT_PLUGIN_BODY')

        if answer and permissions.has_plugin_permission(
                self.user, content_plugin, 'add'):

            # If the question has not been saved, then there will be no
            # Placeholder set-up for this question yet, so, ensure we have saved
            # first.
            if not question.pk:
                question.save()

            if question and question.answer:
                plugin_kwarg = {
                    'placeholder': question.answer,
                    'plugin_type': content_plugin,
                    'language': self.language_code,
                    content_field: answer,
                }
                add_plugin(**plugin_kwarg)

        # Ensure we make an initial revision
        with transaction.atomic():
            with revision_context_manager.create_revision():
                question.save()
                if self.user:
                    revision_context_manager.set_user(self.user)
                revision_context_manager.set_comment(
                    ugettext("Initial version."))

        return question
示例#32
0
    def save(self, commit=True):
        article = super(CreateNewsBlogArticleForm, self).save(commit=commit)

        # If 'content' field has value, create a TextPlugin with same and add it to the PlaceholderField
        content = clean_html(self.cleaned_data.get('content', ''), False)
        if content and permissions.has_plugin_permission(
                self.user, 'TextPlugin', 'add'):
            add_plugin(
                placeholder=article.content,
                plugin_type='TextPlugin',
                language=self.language_code,
                body=content,
            )

        return article
示例#33
0
def new_profile(request, profile_nr):
    if not has_plugin_permission(request.user, "ProfileGridPlugin", "change"):
        raise PermissionDenied
    grid_id = request.GET.get("profilegrid_id", None)
    form = ProfileForm(
        auto_id='id_%s',
        prefix=u'profile_set-{}'.format(profile_nr),
        empty_permitted=True
    )
    grid_field = form.fields['profile_plugin']
    grid_field.widget = HiddenInput()
    grid_field.initial = grid_id
    return render_to_response(
        'admin/profile/profile_form.html',
        {'form': form},
        RequestContext(request)
    )
    def save(self, commit=True):
        dashboard = super(CreateDashboards_appDashboardForm, self).save(commit=False)
        dashboard.owner = self.user
        dashboard.save()

        # If 'content' field has value, create a TextPlugin with same and add it to the PlaceholderField
        content = clean_html(self.cleaned_data.get('content', ''), False)
        if content and permissions.has_plugin_permission(self.user, 'TextPlugin', 'add'):
            add_plugin(
                placeholder=dashboard.content,
                plugin_type='TextPlugin',
                language=self.language_code,
                body=content,
            )




        return dashboard
示例#35
0
def create_default_children_plugins(request, placeholder, lang, parent_plugin, children_conf):
    """
    Create all default children plugins in the given ``placeholder``.
    If a child have children, this function recurse.
    Return all children and grandchildren (etc.) created
    """
    from cms.api import add_plugin
    children = list()
    grandchildren = list()
    for conf in children_conf:
        if not permissions.has_plugin_permission(request.user, conf['plugin_type'], "add"):
            continue
        plugin = add_plugin(placeholder, conf['plugin_type'], lang, **conf['values'])
        plugin.parent = parent_plugin
        plugin.save()
        if 'children' in conf:
            grandchildren+= create_default_children_plugins(request, placeholder, lang, plugin, conf['children'])
        plugin.notify_on_autoadd(request, conf)
        children.append(plugin)
    parent_plugin.notify_on_autoadd_children(request, conf, children)
    return children + grandchildren
示例#36
0
 def _create_default_plugins(placeholder, confs, parent=None):
     """
     Auxillary function that builds all of a placeholder's default plugins
     at the current level and drives the recursion down the tree.
     Returns the plugins at the current level along with all descendants.
     """
     plugins, descendants = [], []
     addable_confs = (conf for conf in confs
                      if has_plugin_permission(request.user,
                                               conf['plugin_type'], 'add'))
     for conf in addable_confs:
         plugin = add_plugin(placeholder, conf['plugin_type'], lang,
                             target=parent, **conf['values'])
         if 'children' in conf:
             args = placeholder, conf['children'], plugin
             descendants += _create_default_plugins(*args)
         plugin.notify_on_autoadd(request, conf)
         plugins.append(plugin)
     if parent:
         parent.notify_on_autoadd_children(request, conf, plugins)
     return plugins + descendants
示例#37
0
文件: plugins.py 项目: Asjohn720/cms
 def _create_default_plugins(placeholder, confs, parent=None):
     """
     Auxillary function that builds all of a placeholder's default plugins
     at the current level and drives the recursion down the tree.
     Returns the plugins at the current level along with all descendants.
     """
     plugins, descendants = [], []
     addable_confs = (conf for conf in confs
                      if has_plugin_permission(request.user,
                                               conf['plugin_type'], 'add'))
     for conf in addable_confs:
         plugin = add_plugin(placeholder, conf['plugin_type'], lang,
                             target=parent, **conf['values'])
         if 'children' in conf:
             args = placeholder, conf['children'], plugin
             descendants += _create_default_plugins(*args)
         plugin.notify_on_autoadd(request, conf)
         plugins.append(plugin)
     if parent:
         parent.notify_on_autoadd_children(request, conf, plugins)
     return plugins + descendants
示例#38
0
    def save(self, **kwargs):
        from cms.api import add_plugin

        new_page = super().save(**kwargs)

        if self.cleaned_data.get("page_type"):
            return new_page

        parent_node = self.cleaned_data.get('parent_node')

        if parent_node and new_page.parent_page.is_page_type:
            # the new page was created under a page-type page
            # set the new page as a page-type too
            new_page.update(
                draft_only=True,
                is_page_type=True,
                in_navigation=False,
            )

        # If the user provided content, then use that instead.
        content = self.cleaned_data.get('content')
        plugin_type = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN')
        plugin_body = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN_BODY')
        slot = get_cms_setting('PAGE_WIZARD_CONTENT_PLACEHOLDER')

        if plugin_type in plugin_pool.plugins and plugin_body:
            if content and permissions.has_plugin_permission(
                    self.user, plugin_type, "add"):
                new_page.rescan_placeholders()
                placeholder = self.get_placeholder(new_page, slot=slot)
                if placeholder:
                    opts = {
                        'placeholder': placeholder,
                        'plugin_type': plugin_type,
                        'language': self.language_code,
                        plugin_body: content,
                    }
                    add_plugin(**opts)
        return new_page
示例#39
0
def create_default_plugins(request, placeholders, template, lang):
    """
    Create all default plugins for the given ``placeholders`` if they have
    a "default_plugins" configuration value in settings.
    return all plugins, children, grandchildren (etc.) created
    """
    from cms.api import add_plugin
    plugins = list()
    for placeholder in placeholders:
        default_plugins = get_placeholder_conf("default_plugins", placeholder.slot, template, None)
        if not default_plugins:
            continue
        if not placeholder.has_add_permission(request):
            continue
        for conf in default_plugins:
            if not permissions.has_plugin_permission(request.user, conf['plugin_type'], "add"):
                continue
            plugin = add_plugin(placeholder, conf['plugin_type'], lang, **conf['values'])
            plugins.append(plugin)
            if 'children' in conf:
                children = create_default_children_plugins(request, placeholder, lang, plugin, conf['children'])
                plugins+=children
            plugin.notify_on_autoadd(request, conf)
    return plugins
示例#40
0
    def save(self, **kwargs):
        from cms.api import create_page, add_plugin
        from cms.cms_wizards import user_has_page_add_permission

        # Check to see if this user has permissions to make this page. We've
        # already checked this when producing a list of wizard entries, but this
        # is to prevent people from possible form-hacking.

        if 'sub_page' in self.cleaned_data:
            sub_page = self.cleaned_data['sub_page']
        else:
            sub_page = False

        if self.page:
            if sub_page:
                parent = self.page
                position = "last-child"
            else:
                parent = self.page.parent
                position = "right"
        else:
            parent = None
            position = "last-child"

        # Before we do this, verify this user has perms to do so.
        if not (self.user.is_superuser or user_has_page_add_permission(
                self.user, self.page, position=position,
                site=self.page.site_id)):
            raise NoPermissionsException(
                _(u"User does not have permission to add page."))

        title = self.cleaned_data['title']
        page = create_page(title=title,
                           template=get_cms_setting('WIZARD_DEFAULT_TEMPLATE'),
                           language=self.language_code,
                           created_by=smart_text(self.user),
                           parent=parent,
                           in_navigation=True,
                           published=False)

        page_type = self.cleaned_data.get("page_type")
        if page_type:
            copy_target = Page.objects.filter(pk=page_type).first()
        else:
            copy_target = None

        if copy_target:
            # If the user selected a page type, copy that.
            if not user_has_view_permission(self.user, copy_target):
                raise PermissionDenied()

            # Copy page attributes
            copy_target._copy_attributes(page, clean=True)
            page.save()

            # Copy contents (for each language)
            for lang in copy_target.get_languages():
                copy_target._copy_contents(page, lang)

            # Copy extensions
            from cms.extensions import extension_pool
            extension_pool.copy_extensions(copy_target, page)

        else:
            # If the user provided content, then use that instead.
            content = self.cleaned_data.get('content')
            if content and permissions.has_plugin_permission(
                    self.user, get_cms_setting('WIZARD_CONTENT_PLUGIN'),
                    "add"):
                placeholder = self.get_first_placeholder(page)
                if placeholder:
                    add_plugin(
                        **{
                            'placeholder': placeholder,
                            'plugin_type': get_cms_setting(
                                'WIZARD_CONTENT_PLUGIN'),
                            'language': self.language_code,
                            get_cms_setting('WIZARD_CONTENT_PLUGIN_BODY'):
                            content
                        })

        return page
示例#41
0
    def save(self, **kwargs):
        from cms.api import create_page, add_plugin

        # Check to see if this user has permissions to make this page. We've
        # already checked this when producing a list of wizard entries, but this
        # is to prevent people from possible form-hacking.

        if 'sub_page' in self.cleaned_data:
            sub_page = self.cleaned_data['sub_page']
        else:
            sub_page = False

        if self.page and sub_page:
            # User is adding a page which will be a direct
            # child of the current page.
            position = 'last-child'
            parent = self.page
            has_perm = user_can_add_subpage(self.user, target=parent)
        elif self.page and self.page.parent_id:
            # User is adding a page which will be a right
            # sibling to the current page.
            position = 'last-child'
            parent = self.page.parent
            has_perm = user_can_add_subpage(self.user, target=parent)
        else:
            parent = None
            position = 'last-child'
            has_perm = user_can_add_page(self.user)

        if not has_perm:
            raise NoPermissionsException(
                _(u"User does not have permission to add page."))

        page = create_page(
            title=self.cleaned_data['title'],
            slug=self.cleaned_data['slug'],
            template=get_cms_setting('PAGE_WIZARD_DEFAULT_TEMPLATE'),
            language=self.language_code,
            created_by=smart_text(self.user),
            parent=parent,
            position=position,
            in_navigation=True,
            published=False
        )

        page_type = self.cleaned_data.get("page_type")
        if page_type:
            copy_target = Page.objects.filter(pk=page_type).first()
        else:
            copy_target = None

        if copy_target:
            # If the user selected a page type, copy that.
            if not copy_target.has_view_permission(self.user):
                raise PermissionDenied()

            # Copy page attributes
            copy_target._copy_attributes(page, clean=True)
            page.save()

            # Copy contents (for each language)
            for lang in copy_target.get_languages():
                copy_target._copy_contents(page, lang)

            # Copy extensions
            from cms.extensions import extension_pool
            extension_pool.copy_extensions(copy_target, page)

        else:
            # If the user provided content, then use that instead.
            content = self.cleaned_data.get('content')
            plugin_type = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN')
            plugin_body = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN_BODY')
            slot = get_cms_setting('PAGE_WIZARD_CONTENT_PLACEHOLDER')

            if plugin_type in plugin_pool.plugins and plugin_body:
                if content and permissions.has_plugin_permission(
                        self.user, plugin_type, "add"):
                    placeholder = self.get_placeholder(page, slot=slot)
                    if placeholder:
                        opts = {
                            'placeholder': placeholder,
                            'plugin_type': plugin_type,
                            'language': self.language_code,
                            plugin_body: content,
                        }
                        add_plugin(**opts)

        # is it the first page? publish it right away
        if not self.page and Page.objects.filter(site_id=page.site_id).count() == 1:
            page.publish(self.language_code)
            Page.set_homepage(page, user=self.user)
        return page
示例#42
0
    def save(self, **kwargs):
        from cms.api import create_page, add_plugin
        from cms.cms_wizards import user_has_page_add_permission

        # Check to see if this user has permissions to make this page. We've
        # already checked this when producing a list of wizard entries, but this
        # is to prevent people from possible form-hacking.

        if 'sub_page' in self.cleaned_data:
            sub_page = self.cleaned_data['sub_page']
        else:
            sub_page = False

        if self.page:
            if sub_page:
                parent = self.page
                position = "last-child"
            else:
                parent = self.page.parent
                position = "right"
        else:
            parent = None
            position = "last-child"

        # Before we do this, verify this user has perms to do so.
        if not (self.user.is_superuser or
                user_has_page_add_permission(self.user, self.page,
                                             position=position,
                                             site=self.page.site_id)):
            raise NoPermissionsException(
                _(u"User does not have permission to add page."))

        title = self.cleaned_data['title']
        page = create_page(
            title=title,
            template=get_cms_setting('WIZARD_DEFAULT_TEMPLATE'),
            language=self.language_code,
            created_by=smart_text(self.user),
            parent=parent,
            in_navigation=True,
            published=False
        )

        page_type = self.cleaned_data.get("page_type")
        if page_type:
            copy_target = Page.objects.filter(pk=page_type).first()
        else:
            copy_target = None

        if copy_target:
            # If the user selected a page type, copy that.
            if not user_has_view_permission(self.user, copy_target):
                raise PermissionDenied()

            # Copy page attributes
            copy_target._copy_attributes(page, clean=True)
            page.save()

            # Copy contents (for each language)
            for lang in copy_target.get_languages():
                copy_target._copy_contents(page, lang)

            # Copy extensions
            from cms.extensions import extension_pool
            extension_pool.copy_extensions(copy_target, page)

        else:
            # If the user provided content, then use that instead.
            content = self.cleaned_data.get('content')
            if content and permissions.has_plugin_permission(
                    self.user, get_cms_setting('WIZARD_CONTENT_PLUGIN'), "add"):
                placeholder = self.get_first_placeholder(page)
                if placeholder:
                    add_plugin(**{
                        'placeholder': placeholder,
                        'plugin_type': get_cms_setting('WIZARD_CONTENT_PLUGIN'),
                        'language': self.language_code,
                        get_cms_setting('WIZARD_CONTENT_PLUGIN_BODY'): content

                    })

        return page
示例#43
0
    def save(self, **kwargs):
        from cms.api import create_page, add_plugin
        from cms.utils.permissions import has_page_add_permission

        # Check to see if this user has permissions to make this page. We've
        # already checked this when producing a list of wizard entries, but this
        # is to prevent people from possible form-hacking.

        if 'sub_page' in self.cleaned_data:
            sub_page = self.cleaned_data['sub_page']
        else:
            sub_page = False

        if self.page:
            if sub_page:
                parent = self.page
                position = "last-child"
            else:
                parent = self.page.parent
                position = "right"
        else:
            parent = None
            position = "last-child"

        # Before we do this, verify this user has perms to do so.
        if not (self.user.is_superuser or
                has_page_add_permission(self.user, self.page,
                                             position=position,
                                             site=self.page.site)):
            raise NoPermissionsException(
                _(u"User does not have permission to add page."))

        page = create_page(
            title=self.cleaned_data['title'],
            slug=self.cleaned_data['slug'],
            template=get_cms_setting('PAGE_WIZARD_DEFAULT_TEMPLATE'),
            language=self.language_code,
            created_by=smart_text(self.user),
            parent=parent,
            in_navigation=True,
            published=False
        )

        page_type = self.cleaned_data.get("page_type")
        if page_type:
            copy_target = Page.objects.filter(pk=page_type).first()
        else:
            copy_target = None

        if copy_target:
            # If the user selected a page type, copy that.
            if not user_has_view_permission(self.user, copy_target):
                raise PermissionDenied()

            # Copy page attributes
            copy_target._copy_attributes(page, clean=True)
            page.save()

            # Copy contents (for each language)
            for lang in copy_target.get_languages():
                copy_target._copy_contents(page, lang)

            # Copy extensions
            from cms.extensions import extension_pool
            extension_pool.copy_extensions(copy_target, page)

        else:
            # If the user provided content, then use that instead.
            content = self.cleaned_data.get('content')
            plugin_type = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN')
            plugin_body = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN_BODY')
            slot = get_cms_setting('PAGE_WIZARD_CONTENT_PLACEHOLDER')

            if plugin_type in plugin_pool.plugins and plugin_body:
                if content and permissions.has_plugin_permission(
                        self.user, plugin_type, "add"):
                    placeholder = self.get_placeholder(page, slot=slot)
                    if placeholder:
                        opts = {
                            'placeholder': placeholder,
                            'plugin_type': plugin_type,
                            'language': self.language_code,
                            plugin_body: content,
                        }
                        add_plugin(**opts)

        # is it home? publish it right away
        if not self.page and page.is_home:
            page.publish(self.language_code)

        if is_installed('reversion'):
            from cms.utils.helpers import make_revision_with_plugins
            from cms.constants import REVISION_INITIAL_COMMENT
            from cms.utils.reversion_hacks import create_revision

            with create_revision():
                make_revision_with_plugins(
                    obj=page,
                    user=self.user,
                    message=ugettext(REVISION_INITIAL_COMMENT),
                )
        return page
示例#44
0
def variables_edit_view(request, plugin_id):
    plugin = get_object_or_404(InheritPageContent, id=plugin_id)

    if not has_plugin_permission(request.user, plugin.plugin_type, "change"):
        raise PermissionDenied

    snippet_plugin_id = None
    if request.method == 'DELETE':
        snippet_plugin_id = QueryDict(request.body).get('snippet_plugin')

    snippet_plugin_id = (snippet_plugin_id
                         or request.REQUEST.get('snippet_plugin'))
    if snippet_plugin_id is None:
        return HttpResponseBadRequest('Snippet plugin missing')

    snippet_plugin = get_object_or_404(SmartSnippetPointer,
                                       id=snippet_plugin_id)
    variables = snippet_plugin.variables.filter(
        snippet_variable__snippet=snippet_plugin.snippet)
    overwrite_variables = None

    if request.method == 'POST':
        variables = variables.select_related('snippet_variable')
        overwrite_variables = []
        for var in variables:
            new_value = request.POST.get("_%s_" % var.snippet_variable.name)
            if new_value is None:
                continue
            try:
                existing_var = OverwriteVariable.objects.get(plugin=plugin,
                                                             variable=var)
                existing_var.value = new_value
                existing_var.save()
                overwrite_variables.append(existing_var)
            except (OverwriteVariable.DoesNotExist, ):
                new_var = OverwriteVariable.objects.create(plugin=plugin,
                                                           variable=var,
                                                           value=new_value)
                overwrite_variables.append(new_var)

    if overwrite_variables is None:
        overwrite_variables = OverwriteVariable.objects.filter(
            plugin=plugin, variable__in=list(variables))

    if request.method == 'DELETE':
        overwrite_variables.delete()
        overwrite_variables = []

    # transform all into Variable instances
    overwrite_as_vars = [v.to_variable() for v in overwrite_variables]
    vars_to_render = {
        var.snippet_variable.name: var
        for var in list(variables) + overwrite_as_vars
    }

    return render_to_response('smartsnippets/variables_widgets.html', {
        'plugin':
        plugin,
        'variables':
        sorted(vars_to_render.values(),
               key=lambda var: var.snippet_variable.name)
    },
                              context_instance=RequestContext(request))
示例#45
0
 def has_move_plugin_permission(self, request, plugin, target_placeholder):
     if not permissions.has_plugin_permission(request.user, plugin.plugin_type, "change"):
         return False
     if not target_placeholder.has_change_permission(request):
         return False
     return True
示例#46
0
 def has_add_plugin_permission(self, request, placeholder, plugin_type):
     if not permissions.has_plugin_permission(request.user, plugin_type, "add"):
         return False
     if not placeholder.has_add_permission(request):
         return False
     return True
示例#47
0
    def save(self, **kwargs):
        from cms.api import create_page, add_plugin

        # Check to see if this user has permissions to make this page. We've
        # already checked this when producing a list of wizard entries, but this
        # is to prevent people from possible form-hacking.

        if 'sub_page' in self.cleaned_data:
            sub_page = self.cleaned_data['sub_page']
        else:
            sub_page = False

        if self.page and sub_page:
            # User is adding a page which will be a direct
            # child of the current page.
            position = 'last-child'
            parent = self.page
            has_perm = user_can_add_subpage(self.user, target=parent)
        elif self.page and self.page.parent_id:
            # User is adding a page which will be a right
            # sibling to the current page.
            position = 'last-child'
            parent = self.page.parent
            has_perm = user_can_add_subpage(self.user, target=parent)
        else:
            parent = None
            position = 'last-child'
            has_perm = user_can_add_page(self.user)

        if not has_perm:
            raise NoPermissionsException(
                _(u"User does not have permission to add page."))

        page = create_page(
            title=self.cleaned_data['title'],
            slug=self.cleaned_data['slug'],
            template=get_cms_setting('PAGE_WIZARD_DEFAULT_TEMPLATE'),
            language=self.language_code,
            created_by=smart_text(self.user),
            parent=parent,
            position=position,
            in_navigation=True,
            published=False
        )

        page_type = self.cleaned_data.get("page_type")
        if page_type:
            copy_target = Page.objects.filter(pk=page_type).first()
        else:
            copy_target = None

        if copy_target:
            # If the user selected a page type, copy that.
            if not copy_target.has_view_permission(self.user):
                raise PermissionDenied()

            # Copy page attributes
            copy_target._copy_attributes(page, clean=True)
            page.save()

            # Copy contents (for each language)
            for lang in copy_target.get_languages():
                copy_target._copy_contents(page, lang)

            # Copy extensions
            from cms.extensions import extension_pool
            extension_pool.copy_extensions(copy_target, page)

        else:
            # If the user provided content, then use that instead.
            content = self.cleaned_data.get('content')
            plugin_type = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN')
            plugin_body = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN_BODY')
            slot = get_cms_setting('PAGE_WIZARD_CONTENT_PLACEHOLDER')

            if plugin_type in plugin_pool.plugins and plugin_body:
                if content and permissions.has_plugin_permission(
                        self.user, plugin_type, "add"):
                    placeholder = self.get_placeholder(page, slot=slot)
                    if placeholder:
                        opts = {
                            'placeholder': placeholder,
                            'plugin_type': plugin_type,
                            'language': self.language_code,
                            plugin_body: content,
                        }
                        add_plugin(**opts)

        # is it home? publish it right away
        if not self.page and page.is_home:
            page.publish(self.language_code)
        return page
示例#48
0
    def save(self, **kwargs):
        from cms.api import create_page, add_plugin
        from cms.utils.permissions import has_page_add_permission

        # Check to see if this user has permissions to make this page. We've
        # already checked this when producing a list of wizard entries, but this
        # is to prevent people from possible form-hacking.

        if 'sub_page' in self.cleaned_data:
            sub_page = self.cleaned_data['sub_page']
        else:
            sub_page = False

        if self.page:
            if sub_page:
                parent = self.page
                position = "last-child"
            else:
                parent = self.page.parent
                position = "right"
        else:
            parent = None
            position = "last-child"

        # Before we do this, verify this user has perms to do so.
        if not (self.user.is_superuser or has_page_add_permission(
                self.user, self.page, position=position, site=self.page.site)):
            raise NoPermissionsException(
                _(u"User does not have permission to add page."))

        page = create_page(
            title=self.cleaned_data['title'],
            slug=self.cleaned_data['slug'],
            template=get_cms_setting('PAGE_WIZARD_DEFAULT_TEMPLATE'),
            language=self.language_code,
            created_by=smart_text(self.user),
            parent=parent,
            in_navigation=True,
            published=False)

        page_type = self.cleaned_data.get("page_type")
        if page_type:
            copy_target = Page.objects.filter(pk=page_type).first()
        else:
            copy_target = None

        if copy_target:
            # If the user selected a page type, copy that.
            if not user_has_view_permission(self.user, copy_target):
                raise PermissionDenied()

            # Copy page attributes
            copy_target._copy_attributes(page, clean=True)
            page.save()

            # Copy contents (for each language)
            for lang in copy_target.get_languages():
                copy_target._copy_contents(page, lang)

            # Copy extensions
            from cms.extensions import extension_pool
            extension_pool.copy_extensions(copy_target, page)

        else:
            # If the user provided content, then use that instead.
            content = self.cleaned_data.get('content')
            plugin_type = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN')
            plugin_body = get_cms_setting('PAGE_WIZARD_CONTENT_PLUGIN_BODY')
            slot = get_cms_setting('PAGE_WIZARD_CONTENT_PLACEHOLDER')

            if plugin_type in plugin_pool.plugins and plugin_body:
                if content and permissions.has_plugin_permission(
                        self.user, plugin_type, "add"):
                    placeholder = self.get_placeholder(page, slot=slot)
                    if placeholder:
                        opts = {
                            'placeholder': placeholder,
                            'plugin_type': plugin_type,
                            'language': self.language_code,
                            plugin_body: content,
                        }
                        add_plugin(**opts)

        # is it home? publish it right away
        if not self.page and page.is_home:
            page.publish(self.language_code)

        if is_installed('reversion'):
            from cms.utils.helpers import make_revision_with_plugins
            from cms.constants import REVISION_INITIAL_COMMENT
            from cms.utils.reversion_hacks import create_revision

            with create_revision():
                make_revision_with_plugins(
                    obj=page,
                    user=self.user,
                    message=ugettext(REVISION_INITIAL_COMMENT),
                )
        return page
示例#49
0
    def edit_plugin(self, request, plugin_id):
        plugin_id = int(plugin_id)
        # get the plugin to edit of bail out
        cms_plugin = get_object_or_404(CMSPlugin, pk=plugin_id)

        if not has_plugin_permission(request.user, cms_plugin.plugin_type, "change"):
            return HttpResponseForbidden(_("You don't have permission to add plugins"))

        # check that the user has permission to change this plugin
        if not cms_plugin.placeholder.has_change_permission(request):
            return HttpResponseForbidden(_("You don't have permission to add content here."))

        instance, plugin_admin = cms_plugin.get_plugin_instance(self.admin_site)

        plugin_admin.cms_plugin_instance = cms_plugin
        plugin_admin.placeholder = cms_plugin.placeholder

        if request.method == "POST":
            # set the continue flag, otherwise will plugin_admin make redirect to list
            # view, which actually does'nt exists
            post_request = request.POST.copy()
            post_request["_continue"] = True
            request.POST = post_request

        if request.POST.get("_cancel", False):
            # cancel button was clicked
            context = {
                "CMS_MEDIA_URL": get_cms_setting("MEDIA_URL"),
                "plugin": cms_plugin,
                "is_popup": True,
                "type": cms_plugin.get_plugin_name(),
                "plugin_id": plugin_id,
                "icon": force_escape(escapejs(cms_plugin.get_instance_icon_src())),
                "alt": force_escape(escapejs(cms_plugin.get_instance_icon_alt())),
                "cancel": True,
            }
            instance = cms_plugin.get_plugin_instance()[0]
            if instance:
                context["name"] = unicode(instance)
            else:
                # cancelled before any content was added to plugin
                cms_plugin.delete()
                context.update({"deleted": True, "name": unicode(cms_plugin)})
            return render_to_response("admin/cms/page/plugin_forms_ok.html", context, RequestContext(request))

        if not instance:
            # instance doesn't exist, call add view
            response = plugin_admin.add_view(request)

        else:
            # already saved before, call change view
            # we actually have the instance here, but since i won't override
            # change_view method, is better if it will be loaded again, so
            # just pass id to plugin_admin
            response = plugin_admin.change_view(request, str(plugin_id))

        if request.method == "POST" and plugin_admin.object_successfully_changed:
            # read the saved object from plugin_admin - ugly but works
            saved_object = plugin_admin.saved_object

            context = {
                "CMS_MEDIA_URL": get_cms_setting("MEDIA_URL"),
                "plugin": saved_object,
                "is_popup": True,
                "name": unicode(saved_object),
                "type": saved_object.get_plugin_name(),
                "plugin_id": plugin_id,
                "icon": force_escape(saved_object.get_instance_icon_src()),
                "alt": force_escape(escapejs(saved_object.get_instance_icon_alt())),
            }
            return render_to_response("admin/cms/page/plugin_forms_ok.html", context, RequestContext(request))

        return response