Ejemplo n.º 1
0
 def render(self, context, instance, placeholder):
     template_vars = {
         'placeholder': placeholder,
     }
     template_vars['object'] = instance
     lang = instance.from_language
     request = None
     if not lang:
         if context.has_key('request'):
             request = context['request']
             lang = get_language_from_request(request)
         else:
             lang = settings.LANGUAGE_CODE
     if instance.from_page:
         page = instance.from_page
     else:
         page = instance.page
     if not instance.page.publisher_is_draft and page.publisher_is_draft:
         page = page.publisher_public
         
     plugins = get_cmsplugin_queryset(request).filter(page=page, language=lang, placeholder__iexact=placeholder, parent__isnull=True).order_by('position').select_related()
     plugin_output = []
     template_vars['parent_plugins'] = plugins 
     for plg in plugins:
         tmpctx = copy.copy(context)
         tmpctx.update(template_vars)
         inst, name = plg.get_plugin_instance()
         outstr = inst.render_plugin(tmpctx, placeholder)
         plugin_output.append(outstr)
     template_vars['parent_output'] = plugin_output
     context.update(template_vars)
     return context
Ejemplo n.º 2
0
def get_admin_menu_item_context(request, page, filtered=False, language=None):
    """
    Used for rendering the page tree, inserts into context everything what
    we need for single item
    """
    has_add_page_permission = page.has_add_permission(request)
    has_move_page_permission = page.has_move_page_permission(request)

    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    metadata = ""
    if get_cms_setting('PERMISSION'):
        # jstree metadata generator
        md = []

        if not has_move_page_permission:
            md.append(('valid_children', False))
            md.append(('draggable', False))
        if md:
            # just turn it into simple javascript object
            metadata = "{" + ", ".join(
                map(
                    lambda e: "%s: %s" %
                    (e[0], isinstance(e[1], bool) and str(e[1]) or e[1].lower(
                    )), md)) + "}"

    has_add_on_same_level_permission = False
    opts = Page._meta
    if get_cms_setting('PERMISSION'):
        if hasattr(request.user, '_global_add_perm_cache'):
            global_add_perm = request.user._global_add_perm_cache
        else:
            global_add_perm = GlobalPagePermission.objects.user_has_add_permission(
                request.user, page.site_id).exists()
            request.user._global_add_perm_cache = global_add_perm
        if request.user.has_perm(
                opts.app_label + '.' +
                get_permission_codename('add', opts)) and global_add_perm:
            has_add_on_same_level_permission = True
    from cms.utils import permissions
    if not has_add_on_same_level_permission and page.parent_id:
        has_add_on_same_level_permission = permissions.has_generic_permission(
            page.parent_id, request.user, "add", page.site_id)
    context = {
        'request': request,
        'page': page,
        'site': site,
        'lang': lang,
        'filtered': filtered,
        'metadata': metadata,
        'preview_language': language,
        'has_change_permission': page.has_change_permission(request),
        'has_publish_permission': page.has_publish_permission(request),
        'has_delete_permission': page.has_delete_permission(request),
        'has_move_page_permission': has_move_page_permission,
        'has_add_page_permission': has_add_page_permission,
        'has_add_on_same_level_permission': has_add_on_same_level_permission,
        'CMS_PERMISSION': get_cms_setting('PERMISSION'),
    }
    return context
Ejemplo n.º 3
0
def get_admin_menu_item_context(request, page, filtered=False):
    """
    Used for rendering the page tree, inserts into context everything what
    we need for single item
    """
    has_add_page_permission = page.has_add_permission(request)
    has_move_page_permission = page.has_move_page_permission(request)
    
    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    #slug = page.get_slug(language=lang, fallback=True) # why was this here ??
    metadata = ""
    if get_cms_setting('PERMISSION'):
        # jstree metadata generator 
        md = []
        
        #if not has_add_page_permission:
        if not has_move_page_permission:
            md.append(('valid_children', False))
            md.append(('draggable', False))
        if md:
            # just turn it into simple javascript object
            metadata = "{" + ", ".join(map(lambda e: "%s: %s" %(e[0], 
                isinstance(e[1], bool) and str(e[1]) or e[1].lower() ), md)) + "}"
        
    has_add_on_same_level_permission = False
    opts = Page._meta
    if get_cms_setting('PERMISSION'):
        perms = has_global_page_permission(request, page.site_id, can_add=True)
        if (request.user.has_perm(opts.app_label + '.' + opts.get_add_permission()) and perms):
            has_add_on_same_level_permission = True

    if page.delete_requested():
        css_class = "publisher_delete_requested"
    elif not page.published:
        css_class = "publisher_draft"
    else:
        css_class = publisher_classes.get(page.publisher_state, "")

    if not has_add_on_same_level_permission and page.parent_id:
        has_add_on_same_level_permission = permissions.has_generic_permission(page.parent_id, request.user, "add", page.site)
    #has_add_on_same_level_permission = has_add_page_on_same_level_permission(request, page)
    context = {
        'page': page,
        'site': site,
        'lang': lang,
        'filtered': filtered,
        'metadata': metadata,
        'css_class': css_class,
        
        'has_change_permission': page.has_change_permission(request),
        'has_publish_permission': page.has_publish_permission(request),
        'has_delete_permission': page.has_delete_permission(request),
        'has_move_page_permission': has_move_page_permission,
        'has_add_page_permission': has_add_page_permission,
        'has_add_on_same_level_permission': has_add_on_same_level_permission,
        'CMS_PERMISSION': get_cms_setting('PERMISSION'),
        'CMS_SHOW_END_DATE': get_cms_setting('SHOW_END_DATE'),
    }
    return context
def render_tag_links(context):
    request = context["request"]
    language = get_language_from_request(request)
    filters = dict(is_published=True, pub_date__lte=datetime.datetime.now(), entrytitle__language=language)
    return {
        'tags': Tag.objects.usage_for_model(Entry, filters=filters)
    }
Ejemplo n.º 5
0
def get_plugins(request, placeholder, lang=None):
    if not placeholder:
        return []
    lang = lang or get_language_from_request(request)
    if not hasattr(placeholder, '_%s_plugins_cache' % lang):
        assign_plugins(request, [placeholder], lang)
    return getattr(placeholder, '_%s_plugins_cache' % lang)
Ejemplo n.º 6
0
    def copy_plugins(self, request):
        if 'history' in request.path or 'recover' in request.path:
            return HttpResponse(str("error"))
        if request.method == "POST":
            copy_from = request.POST['copy_from']
            placeholder_id = request.POST['placeholder']
            placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
            page = get_item_from_placeholder_if_exists(placeholder)
            language = request.POST['language'] or get_language_from_request(request)

            if not page.has_change_permission(request):
                return HttpResponseForbidden(_("You do not have permission to change this page"))
            if not language or not language in [ l[0] for l in settings.CMS_LANGUAGES ]:
                return HttpResponseBadRequest(_("Language must be set to a supported language!"))
            if language == copy_from:
                return HttpResponseBadRequest(_("Language must be different than the copied language!"))
            plugins = list(placeholder.cmsplugin_set.filter(language=copy_from).order_by('tree_id', '-rght'))
            
            copy_plugins_to(plugins, placeholder, language)
            
            if page and "reversion" in settings.INSTALLED_APPS:
                make_revision_with_plugins(page)
                reversion.revision.user = request.user
                reversion.revision.comment = _(u"Copied %(language)s plugins to %(placeholder)s") % {'language':dict(settings.LANGUAGES)[language], 'placeholder':placeholder}
                
            plugin_list = CMSPlugin.objects.filter(language=language, placeholder=placeholder, parent=None).order_by('position')
            return render_to_response('admin/cms/page/widgets/plugin_item.html', {'plugin_list':plugin_list}, RequestContext(request))
        raise Http404
Ejemplo n.º 7
0
    def render(self, context, instance, placeholder):
        template_vars = {
            'placeholder': placeholder,
        }
        template_vars['object'] = instance
        lang = instance.from_language
        request = context.get('request', None)
        if not lang:
            if context.has_key('request'):
                lang = get_language_from_request(request)
            else:
                lang = settings.LANGUAGE_CODE
        if instance.from_page:
            page = instance.from_page
        else:
            page = instance.page
        if not instance.page.publisher_is_draft and page.publisher_is_draft:
            page = page.publisher_public

        plugins = get_cmsplugin_queryset(request).filter(
            placeholder__page=page,
            language=lang,
            placeholder__slot__iexact=placeholder,
            parent__isnull=True).order_by('position').select_related()
        plugin_output = []
        template_vars['parent_plugins'] = plugins
        for plg in plugins:
            tmpctx = copy.copy(context)
            tmpctx.update(template_vars)
            inst, name = plg.get_plugin_instance()
            outstr = inst.render_plugin(tmpctx, placeholder)
            plugin_output.append(outstr)
        template_vars['parent_output'] = plugin_output
        context.update(template_vars)
        return context
Ejemplo n.º 8
0
def page_id_url(context, reverse_id, lang=None):
    """
    Show the url of a page with a reverse id in the right language
    This is mostly used if you want to have a static link in a template to a page
    """
    request = context.get('request', False)
    if not request:
        return {'content':''}
    if lang is None:
        lang = get_language_from_request(request)
    if hasattr(settings, 'CMS_CONTENT_CACHE_DURATION'):
        key = 'page_url_pid:'+reverse_id+'_l:'+str(lang)+'_type:absolute_url'
        url = cache.get(key)
        if not url:
            try:
                page = Page.objects.get(reverse_id=reverse_id)
            except:
                if settings.DEBUG:
                    raise
                else:
                    site = request.site
                    send_mail(_('Reverse ID not found on %(domain)s') % {'domain':site.domain},
                              _("A page_url template tag didn't found a page with the reverse_id %(reverse_id)s\nThe url of the page was: http://%(host)s%(path)s")%{'reverse_id':reverse_id, 'host':request.host, 'path':request.path},
                               settings.DEFAULT_FROM_EMAIL,
                               settings.MANAGERS, 
                               fail_silently=True)

            url = page.get_absolute_url(language=lang)
            cache.set(key, url, settings.CMS_CONTENT_CACHE_DURATION)
    else:
        url = page.get_absolute_url(language=lang)
    if url:
        return {'content':url}
    return {'content':''}
    def render_tag(self, context, static_code, extra_bits, nodelist=None):
        request = context.get('request')

        if not static_code or not request:
            # an empty string was passed in or the variable is not available in the context
            if nodelist:
                return nodelist.render(context)
            return ''

        validate_placeholder_name(static_code)

        toolbar = get_toolbar_from_request(request)
        renderer = toolbar.get_content_renderer()
        alias = self._get_alias(request, static_code, extra_bits)

        if not alias:
            return ''

        # Get draft contents in edit or preview mode?
        get_draft_content = False
        if toolbar.edit_mode_active or toolbar.preview_mode_active:
            get_draft_content = True

        language = get_language_from_request(request)
        placeholder = alias.get_placeholder(language=language, show_draft_content=get_draft_content)

        if placeholder:
            content = renderer.render_placeholder(
                placeholder=placeholder,
                context=context,
                nodelist=nodelist,
            )
            return content
        return ''
Ejemplo n.º 10
0
def assign_plugins(request, placeholders, lang=None):
    """
    Fetch all plugins for the given ``placeholders`` and
    cast them down to the concrete instances in one query
    per type.
    """
    placeholders = list(placeholders)
    if not placeholders:
        return
    lang = lang or get_language_from_request(request)
    request_lang = lang
    if hasattr(request, "current_page") and request.current_page is not None:
        languages = request.current_page.get_languages()
        if not lang in languages and not get_redirect_on_fallback(lang):
            fallbacks = get_fallback_languages(lang)
            for fallback in fallbacks:
                if fallback in languages:
                    request_lang = fallback
                    break
                    # get all plugins for the given placeholders
    qs = get_cmsplugin_queryset(request).filter(
        placeholder__in=placeholders,
        language=request_lang).order_by('placeholder', 'tree_id', 'lft')
    plugin_list = downcast_plugins(qs)

    # split the plugins up by placeholder
    groups = dict((key, list(plugins)) for key, plugins in groupby(
        plugin_list, operator.attrgetter('placeholder_id')))

    for group in groups:
        groups[group] = build_plugin_tree(groups[group])
    for placeholder in placeholders:
        setattr(placeholder, '_%s_plugins_cache' % lang,
                list(groups.get(placeholder.pk, [])))
Ejemplo n.º 11
0
 def __call__(self, lang):
     page_language = get_language_from_request(self.request)
     with force_language(page_language):
         try:
             view = resolve(self.request.path)
         except:
             view = None
     if hasattr(self.request, 'toolbar') and self.request.toolbar.obj:
         with force_language(lang):
             try:
                 return self.request.toolbar.obj.get_absolute_url()
             except:
                 pass
     elif view and not view.url_name in ('pages-details-by-slug', 'pages-root'):
         view_name = view.url_name
         if view.namespace:
             "%s:%s" % (view.namespace, view_name)
         url = None
         # every class-level argument is instantiated
         # before reversing as reverse does not support
         # classes as arguments
         for idx, arg in enumerate(view.args):
             if isinstance(arg, type):
                 view.args[idx] = arg()
         for key, arg in view.kwargs.items():
             if isinstance(arg, type):
                 view.kwargs[key] = arg()
         with force_language(lang):
             try:
                 url = reverse(view_name, args=view.args, kwargs=view.kwargs, current_app=view.app_name)
             except NoReverseMatch:
                 pass
         if url:
             return url
     return '%s%s' % (self.get_page_path(lang), self.app_path)
Ejemplo n.º 12
0
 def get_form_kwargs(self, step=None):
     """This is called by self.get_form()"""
     kwargs = super(WizardCreateView, self).get_form_kwargs()
     kwargs['wizard_user'] = self.request.user
     if self.is_second_step(step):
         kwargs['wizard_page'] = self.get_origin_page()
         kwargs['wizard_language'] = get_language_from_request(self.request)
     else:
         page_pk = self.page_pk or self.request.GET.get('page', None)
         if page_pk and page_pk != 'None':
             kwargs['wizard_page'] = Page.objects.filter(pk=page_pk).first()
         else:
             kwargs['wizard_page'] = None
         kwargs['wizard_language'] = self.request.GET.get(
             'language', get_language_from_request(self.request))
     return kwargs
Ejemplo n.º 13
0
 def get_form_initial(self, step):
     """This is called by self.get_form()"""
     initial = super(WizardCreateView, self).get_form_initial(step)
     if self.is_first_step(step):
         initial['page'] = self.request.GET.get('page')
         initial['language'] = get_language_from_request(self.request)
     return initial
Ejemplo n.º 14
0
def render_placeholder_toolbar(placeholder,
                               context,
                               content,
                               name_fallback=None):
    from cms.plugin_pool import plugin_pool
    request = context['request']
    page = placeholder.page if placeholder else None
    if not page:
        page = getattr(request, 'current_page', None)
    if page:
        template = page.template
        if name_fallback and not placeholder:
            placeholder = Placeholder.objects.create(slot=name_fallback)
            page.placeholders.add(placeholder)
            placeholder.page = page
    else:
        template = None
    if placeholder:
        slot = placeholder.slot
    else:
        slot = None
    installed_plugins = plugin_pool.get_all_plugins(slot, page)
    name = get_placeholder_conf("name", slot, template, title(slot))
    name = _(name)
    context.push()
    context['installed_plugins'] = installed_plugins
    context['language'] = get_language_from_request(request)
    context['placeholder_label'] = name
    context['placeholder'] = placeholder
    context['page'] = page
    toolbar = render_to_string("cms/toolbar/placeholder.html", context)
    context.pop()
    return "".join([toolbar, content])
Ejemplo n.º 15
0
 def __call__(self, lang):
     page_language = get_language_from_request(self.request)
     with force_language(page_language):
         try:
             view = resolve(self.request.path)
         except:
             view = None
     if hasattr(self.request, "toolbar") and self.request.toolbar.obj:
         with force_language(lang):
             try:
                 return self.request.toolbar.obj.get_absolute_url()
             except:
                 pass
     elif view and not view.url_name in ("pages-details-by-slug", "pages-root"):
         view_name = view.url_name
         if view.namespace:
             "%s:%s" % (view.namespace, view_name)
         url = None
         with force_language(lang):
             try:
                 url = reverse(view_name, args=view.args, kwargs=view.kwargs, current_app=view.app_name)
             except NoReverseMatch:
                 pass
         if url:
             return url
     return "%s%s" % (self.get_page_path(lang), self.app_path)
Ejemplo n.º 16
0
    def init_toolbar(self, request):
        self.request = request
        self.is_staff = self.request.user.is_staff
        self.edit_mode = self.is_staff and self.request.session.get("cms_edit", False)
        self.build_mode = self.is_staff and self.request.session.get("cms_build", False)
        self.use_draft = self.is_staff and self.edit_mode or self.build_mode
        self.show_toolbar = self.is_staff or self.request.session.get("cms_edit", False)
        self.login_form = CMSToolbarLoginForm(request=request)
        if self.request.session.get("cms_toolbar_disabled", False):
            self.show_toolbar = False
        if settings.USE_I18N:
            self.language = get_language_from_request(request)
        else:
            self.language = settings.LANGUAGE_CODE

        # We need to store the current language in case the user's preferred language is different.
        self.toolbar_language = self.language

        user_settings = self.get_user_settings()
        if user_settings:
            if (settings.USE_I18N and user_settings.language in dict(settings.LANGUAGES)) or (
                not settings.USE_I18N and user_settings.language == settings.LANGUAGE_CODE
            ):
                self.toolbar_language = user_settings.language
            else:
                user_settings.language = self.language
                user_settings.save()
            self.clipboard = user_settings.clipboard

        if hasattr(self, "toolbars"):
            for key, toolbar in self.toolbars.items():
                self.toolbars[key].request = self.request
Ejemplo n.º 17
0
 def __call__(self, lang):
     page_language = get_language_from_request(self.request)
     with force_language(page_language):
         try:
             view = resolve(self.request.path_info)
         except Resolver404:
             view = None
     if hasattr(self.request, 'toolbar') and self.request.toolbar.obj:
         with force_language(lang):
             try:
                 return self.request.toolbar.obj.get_absolute_url()
             except:  # noqa: E722
                 pass
     elif view and view.url_name not in ('pages-details-by-slug', 'pages-root'):
         view_name = view.url_name
         if view.namespace:
             view_name = "%s:%s" % (view.namespace, view_name)
         url = None
         with force_language(lang):
             try:
                 url = reverse(view_name, args=view.args, kwargs=view.kwargs, current_app=view.app_name)
             except NoReverseMatch:
                 pass
         if url:
             return url
     return '%s%s' % (self.get_page_path(lang), self.app_path)
Ejemplo n.º 18
0
def page_id_url(context, reverse_id, lang=None, site=None):
    """
    Show the url of a page with a reverse id in the right language
    This is mostly used if you want to have a static link in a template to a page
    """
    site_id = get_site_id(site)
    request = context.get('request', False)
    if not request:
        return {'content': ''}

    if request.current_page == "dummy":
        return {'content': ''}

    if lang is None:
        lang = get_language_from_request(request)
    key = 'page_id_url_pid:' + str(reverse_id) + '_l:' + str(
        lang) + '_site:' + str(site_id) + '_type:absolute_url'
    url = cache.get(key)
    if not url:
        try:
            page = get_page_queryset(request).get(reverse_id=reverse_id,
                                                  site=site_id)
            url = page.get_absolute_url(language=lang)
            cache.set(key, url, settings.CMS_CONTENT_CACHE_DURATION)
        except:
            send_missing_mail(reverse_id, request)

    if url:
        return {'content': url}
    return {'content': ''}
Ejemplo n.º 19
0
    def init_toolbar(self, request):
        self.request = request
        self.is_staff = self.request.user.is_staff
        self.edit_mode = self.is_staff and self.request.session.get('cms_edit', False)
        self.build_mode = self.is_staff and self.request.session.get('cms_build', False)
        self.use_draft = self.is_staff and self.edit_mode or self.build_mode
        self.show_toolbar = self.is_staff or self.request.session.get('cms_edit', False)
        self.login_form = CMSToolbarLoginForm(request=request)
        if self.request.session.get('cms_toolbar_disabled', False):
            self.show_toolbar = False
        if settings.USE_I18N:
            self.language = get_language_from_request(request)
        else:
            self.language = settings.LANGUAGE_CODE

        # We need to store the current language in case the user's preferred language is different.
        self.toolbar_language = self.language

        user_settings = self.get_user_settings()
        if user_settings:
            if (settings.USE_I18N and user_settings.language in dict(settings.LANGUAGES)) or (
                    not settings.USE_I18N and user_settings.language == settings.LANGUAGE_CODE):
                self.toolbar_language = user_settings.language
            else:
                user_settings.language = self.language
                user_settings.save()
            self.clipboard = user_settings.clipboard

        if hasattr(self, 'toolbars'):
            for key, toolbar in self.toolbars.items():
                self.toolbars[key].request = self.request
Ejemplo n.º 20
0
def language_chooser(context, template=NOT_PROVIDED, i18n_mode="raw"):
    """
    Displays a language chooser
    - template: template used to render the language chooser
    """
    if template in MARKERS:
        i18n_mode = template
        template = NOT_PROVIDED
    if template is NOT_PROVIDED:
        template = "menu/language_chooser.html"
    if not i18n_mode in MARKERS:
        i18n_mode = "raw"
    try:
        # If there's an exception (500), default context_processors may not be called.
        request = context["request"]
    except KeyError:
        return {"template": "cms/content.html"}
    marker = MARKERS[i18n_mode]
    cms_languages = dict(settings.CMS_LANGUAGES)
    current_lang = get_language()
    site = Site.objects.get_current()
    cache_key = "%s-language-chooser-%s-%s-%s" % (settings.CMS_CACHE_PREFIX, site.pk, current_lang, i18n_mode)
    languages = cache.get(cache_key, [])
    if not languages:
        for lang in settings.CMS_FRONTEND_LANGUAGES:
            if lang in cms_languages:
                languages.append((lang, marker(cms_languages[lang], lang)))
        if current_lang != get_language():
            activate(current_lang)
        cache.set(cache_key, languages)
    lang = get_language_from_request(request, request.current_page)
    context.update({"languages": languages, "current_language": lang, "template": template})
    return context
Ejemplo n.º 21
0
    def render(self, context, instance, placeholder):
        context['object'] = instance
        context['placeholder'] = placeholder

        lang = instance.from_language
        request = context.get('request', None)
        if not lang:
            if 'request' in context:
                lang = get_language_from_request(request)
            else:
                lang = settings.LANGUAGE_CODE

        page = instance.placeholder.page
        from_page = instance.from_page

        if page.publisher_is_draft:
            # If the plugin is being rendered in draft
            # then show only the draft content of the linked page
            from_page = from_page.get_draft_object()
        else:
            # Otherwise show the live content
            from_page = from_page.get_public_object()

        plugins = get_cmsplugin_queryset(request).filter(
            placeholder__page=from_page,
            language=lang,
            placeholder__slot__iexact=placeholder,
            parent__isnull=True
        ).order_by('position').select_related()

        context['parent_plugins'] = plugins
        context['parent_output'] = self._render_plugins(plugins, context)
        return context
Ejemplo n.º 22
0
def page_url(context, page_lookup, lang=None, site=None):
    """
    Show the url of a page with a reverse id in the right language
    This is mostly used if you want to have a static link in a template to a page
    """
    site_id = get_site_id(site)
    request = context.get('request', False)
    if not request:
        return {'content': ''}

    if request.current_page == "dummy":
        return {'content': ''}

    if lang is None:
        lang = get_language_from_request(request)
    cache_key = _get_cache_key('page_url', page_lookup, lang, site_id)+'_type:absolute_url'
    url = cache.get(cache_key)
    if not url:
        page = _get_page_by_untyped_arg(page_lookup, request, site_id)
        if page:
            url = page.get_absolute_url(language=lang)
            cache.set(cache_key, url, settings.CMS_CONTENT_CACHE_DURATION)
    if url:
        return {'content': url}
    return {'content': ''}
Ejemplo n.º 23
0
def _show_placeholder_for_page(context,
                               placeholder_name,
                               page_lookup,
                               lang=None,
                               site=None,
                               cache_result=True):
    """
    Shows the content of a page with a placeholder name and given lookup
    arguments in the given language.
    This is useful if you want to have some more or less static content that is
    shared among many pages, such as a footer.

    See _get_page_by_untyped_arg() for detailed information on the allowed types
    and their interpretation for the page_lookup argument.
    """
    from django.core.cache import cache
    validate_placeholder_name(placeholder_name)

    request = context.get('request', False)
    site_id = get_site_id(site)

    if not request:
        return {'content': ''}
    if lang is None:
        lang = get_language_from_request(request)

    if cache_result:
        base_key = _get_cache_key('_show_placeholder_for_page', page_lookup,
                                  lang, site_id)
        cache_key = _clean_key('%s_placeholder:%s' %
                               (base_key, placeholder_name))
        cached_value = cache.get(cache_key)
        if cached_value:
            restore_sekizai_context(context, cached_value['sekizai'])
            return {'content': mark_safe(cached_value['content'])}
    page = _get_page_by_untyped_arg(page_lookup, request, site_id)
    if not page:
        return {'content': ''}
    try:
        placeholder = page.placeholders.get(slot=placeholder_name)
    except PlaceholderModel.DoesNotExist:
        if settings.DEBUG:
            raise
        return {'content': ''}
    watcher = Watcher(context)
    content = render_placeholder(placeholder,
                                 context,
                                 placeholder_name,
                                 use_cache=cache_result)
    changes = watcher.get_changes()
    if cache_result:
        cache.set(cache_key, {
            'content': content,
            'sekizai': changes
        },
                  get_cms_setting('CACHE_DURATIONS')['content'])

    if content:
        return {'content': mark_safe(content)}
    return {'content': ''}
Ejemplo n.º 24
0
    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(SelectedCategoryInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

        if db_field.name == "category":
            language = get_language_from_request(request)
            field.queryset = models.Category.objects.language(language)
        return field
Ejemplo n.º 25
0
    def get_form(self, request, obj=None, **kwargs):
        """
        Get PageForm for the Page model and modify its fields depending on
        the request.
        """
        if obj:
            if not obj.has_publish_permission(request):
                self.exclude.append('status')
            else:
                if 'status' in self.exclude:
                    self.exclude.remove('status')
            if not obj.has_softroot_permission(request):
                self.exclude.append('soft_root')
            else:
                if 'soft_root' in self.exclude:
                    self.exclude.remove('soft_root')
        version_id = None
        versioned = False
        if "history" in request.path or 'recover' in request.path:
            versioned = True
            version_id = request.path.split("/")[-2]
        form = super(PageAdmin, self).get_form(request, obj, **kwargs)
        language = get_language_from_request(request, obj)
        form.base_fields['language'].initial = force_unicode(language)
        if obj:
            initial_slug = obj.get_slug(language=language, fallback=False, version_id=version_id, force_reload=True)
            initial_title = obj.get_title(language=language, fallback=False, version_id=version_id)
            form.base_fields['slug'].initial = initial_slug
            form.base_fields['title'].initial = initial_title
        else:
            # Clear out the customisations made above
            # TODO - remove this hack, this is v ugly
            form.base_fields['slug'].initial = u''
            form.base_fields['title'].initial = u''

        template = get_template_from_request(request, obj)
        if settings.CMS_TEMPLATES:
            template_choices = list(settings.CMS_TEMPLATES)
            form.base_fields['template'].choices = template_choices
            form.base_fields['template'].initial = force_unicode(template)
        for placeholder in get_placeholders(request, template):
            if placeholder.name not in self.mandatory_placeholders:
                installed_plugins = plugin_pool.get_all_plugins(placeholder.name)
                plugin_list = []
                if obj:
                    if versioned:
                        from reversion.models import Version
                        version = get_object_or_404(Version, pk=version_id)
                        revs = [related_version.object_version for related_version in version.revision.version_set.all()]
                        plugin_list = []
                        for rev in revs:
                            obj = rev.object
                            if obj.__class__ == CMSPlugin:
                                if obj.language == language and obj.placeholder == placeholder.name:
                                    plugin_list.append(rev.object)
                    else:
                        plugin_list = CMSPlugin.objects.filter(page=obj, language=language, placeholder=placeholder.name).order_by('position')
                widget = PluginEditor(attrs={'installed':installed_plugins, 'list':plugin_list})
                form.base_fields[placeholder.name] = CharField(widget=widget, required=False)
        return form
Ejemplo n.º 26
0
def render_placeholder_toolbar(placeholder, context, content, name_fallback=None):
    from cms.plugin_pool import plugin_pool
    request = context['request']
    page = get_page_from_placeholder_if_exists(placeholder)
    if not page:
        page = getattr(request, 'current_page', None)
    if page:
        template = page.template
        if name_fallback and not placeholder:
            placeholder = Placeholder.objects.create(slot=name_fallback)
            page.placeholders.add(placeholder)
    else:
        template = None
    if placeholder:
        slot = placeholder.slot
    else:
        slot = None
    installed_plugins = plugin_pool.get_all_plugins(slot, page)
    mixed_key = "%s %s" % (template, slot)
    name = settings.CMS_PLACEHOLDER_CONF.get(mixed_key, {}).get("name", None)
    if not name:
        name = settings.CMS_PLACEHOLDER_CONF.get(slot, {}).get("name", None)
    if not name:
        name = slot
    if not name:
        name = name_fallback
    name = title(name)
    toolbar = render_to_string("cms/toolbar/add_plugins.html", {
        'installed_plugins': installed_plugins,
        'language': get_language_from_request(request),
        'placeholder_label': name,
        'placeholder': placeholder,
        'page': page,
    })
    return "".join([toolbar, content])
Ejemplo n.º 27
0
 def get_extra_placeholder_menu_items(cls, request, placeholder):
     data = urlencode({
         'placeholder': placeholder.pk,
         'language': get_language_from_request(request),
     })
     return [
         PluginMenuItem(
             _("Export to Clipboard"),
             reverse('admin:export_clipboard_plugins') + '?' + data,
             data={},
             action='modal',
             attributes={
                 'icon': 'export',
             },
         ),
         PluginMenuItem(
             _("Import from Clipboard"),
             reverse('admin:import_clipboard_plugins') + '?' + data,
             data={},
             action='modal',
             attributes={
                 'icon': 'import',
             },
         )
     ]
Ejemplo n.º 28
0
def render_placeholder_toolbar(placeholder, context, content, name_fallback=None):
    from cms.plugin_pool import plugin_pool
    request = context['request']
    page = get_page_from_placeholder_if_exists(placeholder)
    if not page:
        page = getattr(request, 'current_page', None)
    if page:
        template = page.template
        if name_fallback and not placeholder:
            placeholder = Placeholder.objects.create(slot=name_fallback)
            page.placeholders.add(placeholder)
    else:
        template = None
    if placeholder:
        slot = placeholder.slot
    else:
        slot = None
    installed_plugins = plugin_pool.get_all_plugins(slot, page)
    name = get_placeholder_conf(slot, template, "name", title(slot))
    name = _(name)
    context.push()
    context.update({
        'installed_plugins': installed_plugins,
        'language': get_language_from_request(request),
        'placeholder_label': name,
        'placeholder': placeholder,
        'page': page,
    })
    toolbar = render_to_string("cms/toolbar/placeholder.html", context)
    context.pop()
    return "".join([toolbar, content])
Ejemplo n.º 29
0
 def copy_plugins(self, request):
     # only allow POST
     if request.method != "POST":
         raise Http404
     placeholder_id = request.POST['placeholder']
     placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
     
     # check permissions
     if not placeholder.has_add_permission(request):
         raise Http404
     
     # the placeholder actions are responsible for copying, they should return
     # a list of plugins if successful.
     plugins = placeholder.actions.copy(
         target_placeholder=placeholder,
         source_language=request.POST['copy_from'],
         target_language=get_language_from_request(request),
         fieldname=placeholder._get_attached_field_name(),
         model=placeholder._get_attached_model(),
     )
     if plugins:
         return render_to_response('admin/cms/page/widgets/plugin_item.html',
             {'plugin_list': list(plugins)}, RequestContext(request))
     else:
         return HttpResponseBadRequest("Error during copy")
Ejemplo n.º 30
0
    def render(self, context, instance, placeholder):
        request = context.get("request", None)
        if context.has_key("request"):
            lang = get_language_from_request(request)
        else:
            lang = settings.LANGUAGE_CODE

        # Get all FaqEntryPlugins on this page and in this language
        plugins = get_cmsplugin_queryset(request).filter(
            plugin_type="CMSFaqEntryPlugin",
            placeholder__page=instance.page,
            language=lang,
            placeholder__slot__iexact=placeholder,
            parent__isnull=True).order_by("position").select_related()

        faqentry_plugins = []

        # Make a list of the FaqEntry plugin objects
        for plugin in plugins:
            # Truncate the entry's body
            if instance.truncate_body:
                plugin.faqentry.body = truncate_words(plugin.faqentry.body,
                                                      instance.truncate_body)
            # Show the entry's body or not
            if not instance.show_body:
                plugin.faqentry.body = ''
            faqentry_plugins.append(plugin.faqentry)

        context.update({
            "faq_list": faqentry_plugins,
            "css": instance.get_css_display(),
            "placeholder": placeholder,
        })
        return context
Ejemplo n.º 31
0
def page_url(context, page_lookup, lang=None, site=None):
    """
    Show the url of a page with a reverse id in the right language
    This is mostly used if you want to have a static link in a template to a page
    """
    site_id = get_site_id(site)
    request = context.get('request', False)
    if not request:
        return {'content': ''}

    if request.current_page == "dummy":
        return {'content': ''}

    if lang is None:
        lang = get_language_from_request(request)
    cache_key = _get_cache_key('page_url', page_lookup, lang,
                               site_id) + '_type:absolute_url'
    url = cache.get(cache_key)
    if not url:
        page = _get_page_by_untyped_arg(page_lookup, request, site_id)
        if page:
            url = page.get_absolute_url(language=lang)
            cache.set(cache_key, url, settings.CMS_CONTENT_CACHE_DURATION)
    if url:
        return {'content': url}
    return {'content': ''}
Ejemplo n.º 32
0
def get_operations_from_request(request, path=None, language=None):
    from .models import PlaceholderOperation

    if not language:
        language = get_language_from_request(language)

    origin = path or request.path

    # This is controversial :/
    # By design, we don't let undo/redo span longer than a day.
    # To be decided if/how this should be configurable.
    date = timezone.now() - timedelta(days=1)

    site = Site.objects.get_current(request)

    queryset = PlaceholderOperation.objects.filter(
        site=site,
        origin=origin,
        language=language,
        user=request.user,
        user_session_key=request.session.session_key,
        date_created__gt=date,
        is_archived=False,
    )
    return queryset
Ejemplo n.º 33
0
    def get_extra_plugin_menu_items(cls, request, plugin):
        if plugin.plugin_type == cls.__name__:
            return

        data = urlencode({
            'language': get_language_from_request(request),
            'plugin': plugin.pk,
        })
        return [
            PluginMenuItem(
                _('Export plugins'),
                admin_reverse('cms_export_plugins') + '?' + data,
                data={},
                action='none',
                attributes={
                    'icon': 'export',
                },
            ),
            PluginMenuItem(
                _('Import plugins'),
                admin_reverse('cms_import_plugins') + '?' + data,
                data={},
                action='modal',
                attributes={
                    'icon': 'import',
                },
            ),
        ]
Ejemplo n.º 34
0
def render_month_links(context):
    request = context["request"]
    language = get_language_from_request(request)
    kw = get_translation_filter_language(Entry, language)
    return {
        'dates': Entry.published.filter(**kw).dates('pub_date', 'month'),
    }
Ejemplo n.º 35
0
 def get_extra_placeholder_menu_items(cls, request, placeholder):  # noqa
     data = urlencode({
         'language': get_language_from_request(request),
         'placeholder': placeholder.pk,
     })
     return [
         PluginMenuItem(
             _('Export plugins'),
             admin_reverse('cms_export_plugins') + '?' + data,
             data={},
             action='none',
             attributes={
                 'icon': 'export',
             },
         ),
         PluginMenuItem(
             _('Import plugins'),
             admin_reverse('cms_import_plugins') + '?' + data,
             data={},
             action='modal',
             attributes={
                 'icon': 'import',
             },
         )
     ]
Ejemplo n.º 36
0
 def render(self, context):
     if not 'request' in context:
         return ''
     l = get_language_from_request(context['request'])
     request = context['request']
     page = request.current_page
     c = None
     t = None
     if self.name == "title":
         t = Title.objects.get_title(page, l, True)
         if t:
             c = t.title
     elif self.name == "slug":
         t = Title.objects.get_title(page, l, True)
         if t:
             c = t.slug
     else:
         plugins = CMSPlugin.objects.filter(page=page, language=l, placeholder__iexact=self.name).order_by('position').select_related()
         c = ""
         for plugin in plugins:
             c += plugin.render_plugin(context, self.name)
     if not c:
         return ''
     if not t:
         return '<div id="%s" class="placeholder">%s</div>' % (self.name, c)
     return c
Ejemplo n.º 37
0
    def render(self, context, instance, placeholder):
        context['object'] = instance
        context['placeholder'] = placeholder

        lang = instance.from_language
        request = context.get('request', None)
        if not lang:
            if 'request' in context:
                lang = get_language_from_request(request)
            else:
                lang = settings.LANGUAGE_CODE

        page = instance.placeholder.page
        from_page = instance.from_page

        if page.publisher_is_draft:
            # If the plugin is being rendered in draft
            # then show only the draft content of the linked page
            from_page = from_page.get_draft_object()
        else:
            # Otherwise show the live content
            from_page = from_page.get_public_object()

        plugins = get_cmsplugin_queryset(request).filter(
            placeholder__page=from_page,
            language=lang,
            placeholder__slot__iexact=placeholder,
            parent__isnull=True
        ).order_by('position').select_related()

        context['parent_plugins'] = plugins
        context['parent_output'] = self._render_plugins(plugins, context)
        return context
Ejemplo n.º 38
0
    def render(self, context):
        if context.get('display_placeholder_names_only'):
            return "<!-- PlaceholderNode: %s -->" % self.name
        if not 'request' in context:
            return ''
        l = get_language_from_request(context['request'])
        request = context['request']

        page = request.current_page
        if page == "dummy":
            return ""
        plugins = get_cmsplugin_queryset(request).filter(
            page=page,
            language=l,
            placeholder__iexact=self.name,
            parent__isnull=True).order_by('position').select_related()
        if settings.CMS_PLACEHOLDER_CONF and self.name in settings.CMS_PLACEHOLDER_CONF:
            if "extra_context" in settings.CMS_PLACEHOLDER_CONF[self.name]:
                context.update(
                    settings.CMS_PLACEHOLDER_CONF[self.name]["extra_context"])
        if self.theme:
            # this may overwrite previously defined key [theme] from settings.CMS_PLACEHOLDER_CONF
            context.update({
                'theme': self.theme,
            })
        c = []
        for index, plugin in enumerate(plugins):
            context['plugin_index'] = index
            c.append(plugin.render_plugin(context, self.name))
        return "".join(c)
Ejemplo n.º 39
0
def get_admin_menu_item_context(request, page, filtered=False):
    """
    Used for rendering the page tree, inserts into context everything what
    we need for single item
    """
    has_add_page_permission = page.has_add_permission(request)
    has_move_page_permission = page.has_move_page_permission(request)

    site = Site.objects.get_current()
    lang = get_language_from_request(request)
    # slug = page.get_slug(language=lang, fallback=True) # why was this here ??
    metadata = ""
    if settings.CMS_PERMISSION:
        # jstree metadata generator
        md = []

        # if not has_add_page_permission:
        if not has_move_page_permission:
            md.append(("valid_children", False))
            md.append(("draggable", False))
        if md:
            # just turn it into simple javasript object
            metadata = (
                "{"
                + ", ".join(map(lambda e: "%s: %s" % (e[0], isinstance(e[1], bool) and str(e[1]) or e[1].lower()), md))
                + "}"
            )

    moderator_state = moderator.page_moderator_state(request, page)
    has_add_on_same_level_permission = False
    opts = Page._meta
    if request.user.has_perm(
        opts.app_label + "." + opts.get_add_permission()
    ) and GlobalPagePermission.objects.with_user(request.user).filter(can_add=True, sites__in=[page.site_id]):
        has_add_on_same_level_permission = True

    if not has_add_on_same_level_permission and page.parent_id:
        has_add_on_same_level_permission = permissions.has_generic_permission(
            page.parent_id, request.user, "add", page.site
        )
    # has_add_on_same_level_permission = has_add_page_on_same_level_permission(request, page)
    context = {
        "page": page,
        "site": site,
        "lang": lang,
        "filtered": filtered,
        "metadata": metadata,
        "has_change_permission": page.has_change_permission(request),
        "has_publish_permission": page.has_publish_permission(request),
        "has_delete_permission": page.has_delete_permission(request),
        "has_move_page_permission": has_move_page_permission,
        "has_add_page_permission": has_add_page_permission,
        "has_moderate_permission": page.has_moderate_permission(request),
        "page_moderator_state": moderator_state,
        "moderator_should_approve": moderator_state["state"] >= moderator.I_APPROVE,
        "has_add_on_same_level_permission": has_add_on_same_level_permission,
        "CMS_PERMISSION": settings.CMS_PERMISSION,
        "CMS_MODERATOR": settings.CMS_MODERATOR,
    }
    return context
Ejemplo n.º 40
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))
Ejemplo n.º 41
0
    def get_nodes(self, request):
        page_queryset = get_page_queryset(request)
        site = Site.objects.get_current()
        lang = get_language_from_request(request)

        filters = {
            'site': site,
        }

        if hide_untranslated(lang, site.pk):
            filters['title_set__language'] = lang

        if not use_draft(request):
            page_queryset = page_queryset.published(lang)
        pages = page_queryset.filter(**filters).order_by("tree_id", "lft")
        ids = {}
        nodes = []
        first = True
        home_cut = False
        home_children = []
        home = None
        actual_pages = []

        # cache view perms
        visible_pages = get_visible_pages(request, pages, site)
        for page in pages:
            # Pages are ordered by tree_id, therefore the first page is the root
            # of the page tree (a.k.a "home")
            if page.pk not in visible_pages:
                # Don't include pages the user doesn't have access to
                continue
            if not home:
                home = page
            if first and page.pk != home.pk:
                home_cut = True
            if (page.parent_id == home.pk
                    or page.parent_id in home_children) and home_cut:
                home_children.append(page.pk)
            if (page.pk == home.pk
                    and home.in_navigation) or page.pk != home.pk:
                first = False
            ids[page.id] = page
            actual_pages.append(page)
            page.title_cache = {}

        langs = [lang]
        if not hide_untranslated(lang):
            langs.extend(get_fallback_languages(lang))

        titles = list(
            get_title_queryset(request).filter(page__in=ids,
                                               language__in=langs))
        for title in titles:  # add the title and slugs and some meta data
            page = ids[title.page_id]
            page.title_cache[title.language] = title

        for page in actual_pages:
            if page.title_cache:
                nodes.append(page_to_node(page, home, home_cut))
        return nodes
Ejemplo n.º 42
0
def show_placeholder_by_id(context, placeholder_name, reverse_id, lang=None, site=None):
    """
    Show the content of a page with a placeholder name and a reverse id in the right language
    This is mostly used if you want to have static content in a template of a page (like a footer)
    """
    request = context.get('request', False)
    site_id = get_site_id(site)
    
    if not request:
        return {'content':''}
    if lang is None:
        lang = get_language_from_request(request)
    key = 'show_placeholder_by_id_pid:'+reverse_id+'_placeholder:'+placeholder_name+'_site:'+str(site_id)+'_l:'+str(lang)
    content = cache.get(key)
    if not content:
        try:
            page = get_page_queryset(request).get(reverse_id=reverse_id, site=site_id)
        except:
            send_missing_mail(reverse_id, request)
            return {'content':''}
        plugins = get_cmsplugin_queryset(request).filter(page=page, language=lang, placeholder__iexact=placeholder_name, parent__isnull=True).order_by('position').select_related()
        content = ""
        for plugin in plugins:
            content += plugin.render_plugin(context, placeholder_name)

    cache.set(key, content, settings.CMS_CONTENT_CACHE_DURATION)

    if content:
        return {'content':mark_safe(content)}
    return {'content':''}
Ejemplo n.º 43
0
 def render(self, name, value, attrs=None):
     try:
         ph = Placeholder.objects.get(pk=value)
     except Placeholder.DoesNotExist:
         ph = None
         context = {'add': True}
     if ph:
         plugin_list = ph.cmsplugin_set.filter(
             parent=None).order_by('position')
         plugin_list = self.filter_func(self.request, plugin_list)
         language = get_language_from_request(self.request)
         copy_languages = []
         if ph.actions.can_copy:
             copy_languages = ph.actions.get_copy_languages(
                 placeholder=ph,
                 model=ph._get_attached_model(),
                 fieldname=ph._get_attached_field_name())
         context = {
             'plugin_list': plugin_list,
             'installed_plugins': plugin_pool.get_all_plugins(ph.slot),
             'copy_languages': copy_languages,
             'language': language,
             'show_copy': bool(copy_languages) and ph.actions.can_copy,
             'urloverride': True,
             'placeholder': ph,
         }
     #return mark_safe(render_to_string(
     #    'admin/cms/page/widgets/plugin_editor.html', context))
     return mark_safe(
         render_to_string('admin/cms/page/widgets/placeholder_editor.html',
                          context))
Ejemplo n.º 44
0
 def save_model(self, request, obj, form, change):
     """
     Given a model instance save it to the database.
     """
     super(EntryAdmin, self).save_model(request, obj, form, change)
     language = get_language_from_request(request)
     EntryTitle.objects.filter(entry=obj, language=language, author=None).update(author=request.user)
Ejemplo n.º 45
0
def get_plugins(request, placeholder, lang=None):
    if not placeholder:
        return []
    lang = lang or get_language_from_request(request)
    if not hasattr(placeholder, '_%s_plugins_cache' % lang):
        assign_plugins(request, [placeholder], lang)
    return getattr(placeholder, '_%s_plugins_cache' % lang)
Ejemplo n.º 46
0
 def category(self):
     if not self._category:
         language = get_language_from_request(self.request)
         self._category = BlogCategory._default_manager.language(language).get(
             translations__language_code=language,
             translations__slug=self.kwargs['category'])
     return self._category
Ejemplo n.º 47
0
def assign_plugins(request, placeholders, lang=None):
    """
    Fetch all plugins for the given ``placeholders`` and
    cast them down to the concrete instances in one query
    per type.
    """
    placeholders = list(placeholders)
    if not placeholders:
        return
    lang = lang or get_language_from_request(request)
    request_lang = lang
    if hasattr(request, "current_page") and request.current_page is not None:
        languages = request.current_page.get_languages()
        if not lang in languages and not get_redirect_on_fallback(lang):
            fallbacks = get_fallback_languages(lang)
            for fallback in fallbacks:
                if fallback in languages:
                    request_lang = fallback
                    break
                    # get all plugins for the given placeholders
    qs = get_cmsplugin_queryset(request).filter(placeholder__in=placeholders, language=request_lang).order_by(
        'placeholder', 'tree_id', 'lft')
    plugin_list = downcast_plugins(qs)

    # split the plugins up by placeholder
    groups = dict((key, list(plugins)) for key, plugins in groupby(plugin_list, operator.attrgetter('placeholder_id')))

    for group in groups:
        groups[group] = build_plugin_tree(groups[group])
    for placeholder in placeholders:
        setattr(placeholder, '_%s_plugins_cache' % lang, list(groups.get(placeholder.pk, [])))
Ejemplo n.º 48
0
    def get_value(self, context, page_lookup, lang, site):
        from django.core.cache import cache

        site_id = get_site_id(site)
        request = context.get('request', False)

        if not request:
            return ''

        if lang is None:
            lang = get_language_from_request(request)

        cache_key = _get_cache_key('page_url', page_lookup, lang, site_id) + \
            '_type:absolute_url'

        url = cache.get(cache_key)

        if not url:
            page = _get_page_by_untyped_arg(page_lookup, request, site_id)
            if page:
                url = page.get_absolute_url(language=lang)
                cache.set(cache_key, url,
                          get_cms_setting('CACHE_DURATIONS')['content'])
        if url:
            return url
        return ''
Ejemplo n.º 49
0
    def get_value(self, context, page_lookup, lang, site):
        from django.core.cache import cache

        site_id = get_site_id(site)
        request = context.get('request', False)

        if not request:
            return ''

        if lang is None:
            lang = get_language_from_request(request)

        cache_key = _get_cache_key('page_url', page_lookup, lang, site_id) + \
            '_type:absolute_url'

        url = cache.get(cache_key)

        if not url:
            page = _get_page_by_untyped_arg(page_lookup, request, site_id)
            if page:
                url = page.get_absolute_url(language=lang)
                cache.set(cache_key, url,
                          get_cms_setting('CACHE_DURATIONS')['content'])
        if url:
            return url
        return ''
Ejemplo n.º 50
0
def get_language_from_context(context):
    if 'LANGUAGE_CODE' in context:
        return context['LANGUAGE_CODE']
    elif 'request' in context:
        return get_language_from_request(context['request'])
    else:
        return get_language() or settings.LANGUAGE_CODE
Ejemplo n.º 51
0
    def add_wizard_button(self):
        from cms.wizards.wizard_pool import entry_choices
        title = _("Create")
        try:
            page_pk = self.page.pk
        except AttributeError:
            page_pk = ''

        user = getattr(self.request, "user", None)
        disabled = user and hasattr(self, "page") and len(
            list(entry_choices(user, self.page))) == 0

        lang = get_language_from_request(
            self.request, current_page=self.page) or get_default_language()

        url = '{url}?page={page}&language={lang}&edit'.format(
            url=reverse("cms_wizard_create"),
            page=page_pk,
            lang=lang,
        )
        self.toolbar.add_modal_button(title,
                                      url,
                                      side=self.toolbar.RIGHT,
                                      disabled=disabled,
                                      on_close=REFRESH_PAGE)
Ejemplo n.º 52
0
    def get_resource_url(self, res, href, **kwargs):
        if res.id is None or not res.realm:
            raise resource.ResourceNotFound()
        elif res.realm == 'filer':
            try:
                link = self._get_file(res).url
            except filer_models.File.DoesNotExist as e:
                raise resource.ResourceNotFound(e)
        elif res.realm == 'blog':
            try:
                link = self._get_blog(res).get_absolute_url()
            except blog_models.EntryTitle.DoesNotExist as e:
                raise resource.ResourceNotFound(e)
        elif res.realm == 'cms':
            try:
                request = _get_django_request(res=res)
                lang = cms_utils.get_language_from_request(request)
                link = self._get_page(res).get_absolute_url(language=lang)
            except cms_models.Page.DoesNotExist as e:
                # Test again as maybe we got [cms: this page] link but we could not get current page
                if not res.id:
                    raise resource.ResourceNotFound(e)

                try:
                    link = urlresolvers.reverse(res.id)
                except urlresolvers.NoReverseMatch as e:
                    raise resource.ResourceNotFound(e)
        else:
            raise RuntimeError("This should be impossible")
        
        args = [link]
        if link.endswith('/') and not link.strip('/') == '':
            # We add an empty link component at the end to force trailing slash
            args.append('')
        return href(*args, **kwargs)
Ejemplo n.º 53
0
def render_month_links(context):
    request = context["request"]
    language = get_language_from_request(request)
    kw = get_translation_filter_language(Entry, language)
    return {
        'dates': Entry.published.filter(**kw).dates('pub_date', 'month'),
    }
Ejemplo n.º 54
0
 def render(self, name, value, attrs=None):
     try:
         ph = Placeholder.objects.get(pk=value)
     except Placeholder.DoesNotExist:
         ph = None
         context = {'add':True}
     if ph:
         plugin_list = ph.cmsplugin_set.filter(parent=None).order_by('position')
         plugin_list = self.filter_func(self.request, plugin_list)
         language = get_language_from_request(self.request)
         copy_languages = []
         if ph.actions.can_copy:
             copy_languages = ph.actions.get_copy_languages(
                 placeholder=ph,
                 model=ph._get_attached_model(),
                 fieldname=ph._get_attached_field_name()
             )
         context = {
             'plugin_list': plugin_list,
             'installed_plugins': plugin_pool.get_all_plugins(ph.slot),
             'copy_languages': copy_languages, 
             'language': language,
             'show_copy': bool(copy_languages) and ph.actions.can_copy,
             'urloverride': True,
             'placeholder': ph,
         }
     #return mark_safe(render_to_string(
     #    'admin/cms/page/widgets/plugin_editor.html', context))
     return mark_safe(render_to_string(
         'admin/cms/page/widgets/placeholder_editor.html', context, RequestContext(self.request)))
Ejemplo n.º 55
0
 def __call__(self, lang):
     page_language = get_language_from_request(self.request)
     with force_language(page_language):
         try:
             view = resolve(self.request.path)
         except:
             view = None
     if hasattr(self.request, 'toolbar') and self.request.toolbar.obj:
         with force_language(lang):
             try:
                 return self.request.toolbar.obj.get_absolute_url()
             except:
                 pass
     elif view and not view.url_name in ('pages-details-by-slug', 'pages-root'):
         view_name = view.url_name
         if view.namespace:
             view_name = "%s:%s" % (view.namespace, view_name)
         url = None
         with force_language(lang):
             with static_stringifier(view):  # This is a fix for Django < 1.7
                 try:
                     url = reverse(view_name, args=view.args, kwargs=view.kwargs, current_app=view.app_name)
                 except NoReverseMatch:
                     pass
         if url:
             return url
     return '%s%s' % (self.get_page_path(lang), self.app_path)
Ejemplo n.º 56
0
def page_id_url(context, reverse_id, lang=None, site=None):
    """
    Show the url of a page with a reverse id in the right language
    This is mostly used if you want to have a static link in a template to a page
    """
    site_id = get_site_id(site)
    request = context.get('request', False)
    if not request:
        return {'content':''}

    if request.current_page == "dummy":
        return {'content': ''}
    
    if lang is None:
        lang = get_language_from_request(request)
    key = 'page_id_url_pid:'+str(reverse_id)+'_l:'+str(lang)+'_site:'+str(site_id)+'_type:absolute_url'
    url = cache.get(key)
    if not url:
        try:
            page = get_page_queryset(request).get(reverse_id=reverse_id,site=site_id)
            url = page.get_absolute_url(language=lang)
            cache.set(key, url, settings.CMS_CONTENT_CACHE_DURATION)
        except:
            send_missing_mail(reverse_id, request)
        
    if url:
        return {'content':url}
    return {'content':''}
Ejemplo n.º 57
0
 def get_context(self, context, lang):
     try:
         # If there's an exception (500), default context_processors may not be called.
         request = context['request']
     except KeyError:
         return {'template': 'cms/content.html'}
     if hasattr(request, "_language_changer"):
         try:
             setattr(request._language_changer, 'request', request)
         except AttributeError:
             pass
         url = "/%s" % lang + request._language_changer(lang)
     else:
         page = request.current_page
         if page == "dummy":
             return {'content': ''}
         try:
             url = page.get_absolute_url(language=lang, fallback=False)
             url = "/" + lang + url
         except:
             # no localized path/slug. 
             url = ''
         if page.get_application_urls():
             # determine which part of the current url belongs to the app
             curLang = get_language_from_request(request)
             curPageUrl = page.get_absolute_url(language=curLang, fallback=False)
             curPath = request.path_info
             appPath = curPath[ len(curPageUrl) :]
             url += appPath
     return {'content':url}
Ejemplo n.º 58
0
 def copy_plugins(self, request):
     # only allow POST
     if request.method != "POST":
         raise Http404
     placeholder_id = request.POST['placeholder']
     placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
     
     # check permissions
     if not placeholder.has_add_permission(request):
         raise Http404
     
     # the placeholder actions are responsible for copying, they should return
     # a list of plugins if successful.
     plugins = placeholder.actions.copy(
         target_placeholder=placeholder,
         source_language=request.POST['copy_from'],
         target_language=get_language_from_request(request),
         fieldname=placeholder._get_attached_field_name(),
         model=placeholder._get_attached_model(),
     )
     if plugins:
         return render_to_response('admin/cms/page/widgets/plugin_item.html',
             {'plugin_list': list(plugins)}, RequestContext(request))
     else:
         return HttpResponseBadRequest("Error during copy")
Ejemplo n.º 59
0
def render_placeholder_toolbar(placeholder, context, content):
    from cms.plugin_pool import plugin_pool
    request = context['request']
    page = get_page_from_placeholder_if_exists(placeholder)
    if page:
        template = page.template
    else:
        template = None
    installed_plugins = plugin_pool.get_all_plugins(placeholder.slot, page)
    name = settings.CMS_PLACEHOLDER_CONF.get(
        "%s %s" % (template, placeholder.slot), {}).get("name", None)
    if not name:
        name = settings.CMS_PLACEHOLDER_CONF.get(placeholder.slot,
                                                 {}).get("name", None)
    if not name:
        name = placeholder.slot
    name = title(name)
    toolbar = render_to_string(
        "cms/toolbar/add_plugins.html", {
            'installed_plugins': installed_plugins,
            'language': get_language_from_request(request),
            'placeholder_label': name,
            'placeholder': placeholder,
            'page': page,
        })
    return "".join([toolbar, content])