def get_context(self, context, obj): # Prepend frontedit toolbar output if applicable request = context['request'] items = [] if isinstance(obj, CMSPlugin): plugin = obj plugin_class_inst = plugin.get_plugin_class_instance() item = plugin_class_inst.get_extra_local_plugin_menu_items(request, plugin) if item: items += item plugin_classes = plugin_pool.get_all_plugins() for plugin_class in plugin_classes: plugin_class_inst = plugin_class() item = plugin_class_inst.get_extra_global_plugin_menu_items(request, plugin) if item: items += item elif isinstance(obj, PlaceholderModel): plugin_classes = plugin_pool.get_all_plugins() for plugin_class in plugin_classes: plugin_class_inst = plugin_class() item = plugin_class_inst.get_extra_placeholder_menu_items(request, obj) if item: items += item return {'items': items}
def render_placeholder_toolbar(placeholder, context, name_fallback, save_language): 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: if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) placeholder.page = page if placeholder: slot = placeholder.slot else: slot = None context.push() all_plugins = plugin_pool.get_all_plugins() plugin_types = [cls.__name__ for cls in plugin_pool.get_all_plugins(slot, page)] context['allowed_plugins'] = plugin_types + plugin_pool.get_system_plugins() context['plugin_menu'] = get_toolbar_plugin_struct(all_plugins, slot=slot, page=page) context['placeholder'] = placeholder context['language'] = save_language context['page'] = page toolbar = render_to_string("cms/toolbar/placeholder.html", flatten_context(context)) context.pop() return toolbar
def render_placeholder_toolbar(placeholder, context, name_fallback, save_language): 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: if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) placeholder.page = page if placeholder: slot = placeholder.slot else: slot = None context.push() all_plugins = plugin_pool.get_all_plugins() plugin_types = [ cls.__name__ for cls in plugin_pool.get_all_plugins(slot, page) ] context['allowed_plugins'] = plugin_types + plugin_pool.get_system_plugins( ) context['plugin_menu'] = get_toolbar_plugin_struct(all_plugins, slot=slot, page=page) context['placeholder'] = placeholder context['language'] = save_language context['page'] = page toolbar = render_to_string("cms/toolbar/placeholder.html", flatten_context(context)) context.pop() return toolbar
def get_context(self, context, obj): # Prepend frontedit toolbar output if applicable request = context['request'] items = [] if isinstance(obj, CMSPlugin): plugin = obj plugin_class_inst = plugin.get_plugin_class_instance() item = plugin_class_inst.get_extra_local_plugin_menu_items( request, plugin) if item: items.append(item) plugin_classes = plugin_pool.get_all_plugins() for plugin_class in plugin_classes: plugin_class_inst = plugin_class() item = plugin_class_inst.get_extra_global_plugin_menu_items( request, plugin) if item: items += item elif isinstance(obj, PlaceholderModel): plugin_classes = plugin_pool.get_all_plugins() for plugin_class in plugin_classes: plugin_class_inst = plugin_class() item = plugin_class_inst.get_extra_placeholder_menu_items( request, obj) if item: items += item return {'items': items}
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 # Builds the list of dictionaries containing module, name and value for the plugin dropdowns installed_plugins = get_toolbar_plugin_struct(plugin_pool.get_all_plugins(slot, page), slot, page) name = get_placeholder_conf("name", slot, template, title(slot)) name = _(name) context.push() context["installed_plugins"] = installed_plugins ## to restrict child-only plugins from draggables.. context["allowed_plugins"] = [cls.__name__ for cls in plugin_pool.get_all_plugins(slot, page)] context["language"] = get_language_from_request(request) context["placeholder_label"] = name context["placeholder"] = placeholder context["page"] = page toolbar = render_to_string("cms/toolbar/placeholder_bar.html", context) context.pop() return toolbar
def test_08_unregister_non_existing_plugin_should_raise(self): number_of_plugins_before = len(plugin_pool.get_all_plugins()) raised = False try: # There should not be such a plugin registered if the others tests # don't leak plugins plugin_pool.unregister_plugin(DumbFixturePlugin) except PluginNotRegistered: raised = True self.assertTrue(raised) # Let's count, to make sure we didn't remove a plugin accidentally. number_of_plugins_after = len(plugin_pool.get_all_plugins()) self.assertEqual(number_of_plugins_before, number_of_plugins_after)
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])
def search(self, q, language=None, current_site_only=True): """Simple search function Plugins can define a 'search_fields' tuple similar to ModelAdmin classes """ from cms.plugin_pool import plugin_pool qs = self.get_queryset() qs = qs.public() if current_site_only: site = Site.objects.get_current() qs = qs.filter(site=site) qt = Q(title_set__title__icontains=q) # find 'searchable' plugins and build query qp = Q() plugins = plugin_pool.get_all_plugins() for plugin in plugins: cmsplugin = plugin.model if not (hasattr(cmsplugin, "search_fields") and hasattr(cmsplugin, "cmsplugin_ptr")): continue field = cmsplugin.cmsplugin_ptr.field related_query_name = field.related_query_name() if related_query_name and not related_query_name.startswith("+"): for field in cmsplugin.search_fields: qp |= Q(**{"placeholders__cmsplugin__{0}__{1}__icontains".format(related_query_name, field): q}) if language: qt &= Q(title_set__language=language) qp &= Q(cmsplugin__language=language) qs = qs.filter(qt | qp) return qs.distinct()
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) toolbar = render_to_string( "cms/toolbar/placeholder.html", { "installed_plugins": installed_plugins, "language": get_language_from_request(request), "placeholder_label": name, "placeholder": placeholder, "page": page, }, ) return "".join([toolbar, content])
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])
def render_placeholder_toolbar(placeholder, context, name_fallback, save_language): 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: if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) placeholder.page = page if placeholder: slot = placeholder.slot else: slot = None context.push() # to restrict child-only plugins from draggables.. context['allowed_plugins'] = [ cls.__name__ for cls in plugin_pool.get_all_plugins(slot, page) ] context['placeholder'] = placeholder context['language'] = save_language context['page'] = page toolbar = render_to_string("cms/toolbar/placeholder.html", context) context.pop() return toolbar
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, include_page_only=False), "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)) )
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])
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))
def discover(self): ''' Find and register any SegmentPlugins already configured in the CMS and register them. ''' # # To reduce the number of queries we'll be making against CMSPlugin, # let's build a set of eligible plugin_types. This part should not hit # the database at all (provided that the plugin_pool is already # populated.) # # In this case, 'eligible' means that the plugin class subclasses # SegmentPluginBase and that it has allow_overrides = True. Segment # plugins that have allow_overrides = False are not registered. # plugin_types = [] for plugin_class in plugin_pool.get_all_plugins(): if (issubclass(plugin_class, SegmentPluginBase) and plugin_class.allow_overrides): plugin_types.append(plugin_class.__name__) # # Process the plugins that are one of these types. # for plugin_instance in CMSPlugin.objects.filter( plugin_type__in=plugin_types): # # Get the instance as an instance of its proper class rather than # this CMSPlugin object. # plugin_instance = plugin_instance.get_plugin_instance()[0] self.register_segment_plugin(plugin_instance, suppress_discovery=True)
def get_context(self, context, obj): # Prepend frontedit toolbar output if applicable request = context['request'] page = request.current_page child_plugin_classes = [] if isinstance(obj, CMSPlugin): slot = context['slot'] plugin = obj plugin_class = plugin.get_plugin_class() if plugin_class.allow_children: instance, plugin = plugin.get_plugin_instance() childs = [ plugin_pool.get_plugin(cls) for cls in plugin.get_child_classes(slot, page) ] # Builds the list of dictionaries containing module, name and value for the plugin dropdowns child_plugin_classes = get_toolbar_plugin_struct( childs, slot, page, parent=plugin_class) elif isinstance(obj, PlaceholderModel): placeholder = obj page = placeholder.page if placeholder else None if not page: page = getattr(request, 'current_page', None) if placeholder: slot = placeholder.slot else: slot = None # Builds the list of dictionaries containing module, name and value for the plugin dropdowns child_plugin_classes = get_toolbar_plugin_struct( plugin_pool.get_all_plugins(slot, page), slot, page) return {'plugin_classes': child_plugin_classes}
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])
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)))
def search(self, q, language=None, current_site_only=True): """Simple search function Plugins can define a 'search_fields' tuple similar to ModelAdmin classes """ from cms.plugin_pool import plugin_pool qs = self.get_query_set() qs = qs.public() if current_site_only: site = Site.objects.get_current() qs = qs.filter(site=site) qt = Q(title_set__title__icontains=q) # find 'searchable' plugins and build query qp = Q() plugins = plugin_pool.get_all_plugins() for plugin in plugins: cmsplugin = plugin.model if hasattr(cmsplugin, 'search_fields'): for field in cmsplugin.search_fields: qp |= Q(**{'placeholders__cmsplugin__%s__%s__icontains' % \ (cmsplugin.__name__.lower(), field): q}) if language: qt &= Q(title_set__language=language) qp &= Q(cmsplugin__language=language) qs = qs.filter(qt | qp) return qs.distinct()
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
def render_placeholder_toolbar(placeholder, context, name_fallback, save_language): 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: if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) placeholder.page = page if placeholder: slot = placeholder.slot else: slot = None context.push() # to restrict child-only plugins from draggables.. context['allowed_plugins'] = [cls.__name__ for cls in plugin_pool.get_all_plugins(slot, page)] context['placeholder'] = placeholder context['language'] = save_language context['page'] = page toolbar = render_to_string("cms/toolbar/placeholder.html", context) context.pop() return toolbar
def discover(self): ''' Find and register any SegmentPlugins already configured in the CMS and register them. ''' # # To reduce the number of queries we'll be making against CMSPlugin, # let's build a set of eligible plugin_types. This part should not hit # the database at all (provided that the plugin_pool is already # populated.) # # In this case, 'eligible' means that the plugin class subclasses # SegmentPluginBase and that it has allow_overrides = True. Segment # plugins that have allow_overrides = False are not registered. # plugin_types = [] for plugin_class in plugin_pool.get_all_plugins(): if (issubclass(plugin_class, SegmentPluginBase) and plugin_class.allow_overrides): plugin_types.append(plugin_class.__name__) # # Process the plugins that are one of these types. # for plugin_instance in CMSPlugin.objects.filter(plugin_type__in=plugin_types): # # Get the instance as an instance of its proper class rather than # this CMSPlugin object. # plugin_instance = plugin_instance.get_plugin_instance()[0] self.register_segment_plugin(plugin_instance, suppress_discovery=True)
def _get_text_editor_widget(): installed_plugins = plugin_pool.get_all_plugins() plugins = [plugin for plugin in installed_plugins if plugin.text_enabled] try: from cms.plugins.text.widgets.ckeditor_widget import CKEditor return CKEditor(installed_plugins=plugins) except ImportError: pass if USE_TINYMCE and "tinymce" in settings.INSTALLED_APPS: from cms.plugins.text.widgets.tinymce_widget import TinyMCEEditor return TinyMCEEditor(installed_plugins=plugins, mce_attrs={ 'theme_advanced_buttons1': ( 'forecolor, bold, italic, underline, link, unlink, numlist, ' 'bullist, outdent, indent, formatselect, image, code'), 'theme_advanced_buttons2_add': ( 'justifyleft, justifycenter, justifyright, justifyfull,' 'fontselect, fontsizeselect'), 'theme_advanced_buttons3_add': ( 'strikethrough, sub, sup, fullscreen'), 'theme_advanced_toolbar_location': 'top', 'theme_advanced_toolbar_align': 'left', 'setup': 'tinyMCESetup' }) else: return WYMEditor(installed_plugins=plugins)
def get_child_classes(self, slot, page): from cms.plugin_pool import plugin_pool if self.child_classes: return self.child_classes else: installed_plugins = plugin_pool.get_all_plugins(slot, page) return [cls.__name__ for cls in installed_plugins]
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])
def get_context(self, context, obj): # Prepend frontedit toolbar output if applicable request = context['request'] page = request.current_page child_plugin_classes = [] if isinstance(obj, CMSPlugin): slot = context['slot'] plugin = obj plugin_class = plugin.get_plugin_class() if plugin_class.allow_children: instance, plugin = plugin.get_plugin_instance() plugin.cms_plugin_instance = instance childs = [plugin_pool.get_plugin(cls) for cls in plugin.get_child_classes(slot, page)] # Builds the list of dictionaries containing module, name and value for the plugin dropdowns child_plugin_classes = get_toolbar_plugin_struct(childs, slot, page, parent=plugin_class) elif isinstance(obj, PlaceholderModel): placeholder = obj page = placeholder.page if placeholder else None if not page: page = getattr(request, 'current_page', None) if placeholder: slot = placeholder.slot else: slot = None # Builds the list of dictionaries containing module, name and value for the plugin dropdowns child_plugin_classes = get_toolbar_plugin_struct(plugin_pool.get_all_plugins(slot, page), slot, page) return {'plugin_classes': child_plugin_classes}
def _child_classes(self): """All registered plugins shall be allowed as children for this plugin""" result = list(getattr(self, 'generic_child_classes', [])) or [] for p in plugin_pool.get_all_plugins(): if isinstance(p.parent_classes, (list, tuple)) and self.__class__.__name__ in p.parent_classes \ and p.__name__ not in result: result.append(p.__name__) return result
def _plugins_for_site(): cascade_plugins = set([ p for p in plugin_pool.get_all_plugins() if issubclass(p, ExtraFieldsMixin) ]) return [(p.__name__, '{0} {1}'.format(force_text(p.module), force_text(p.name))) for p in cascade_plugins]
def test_07_register_plugin_twice_should_raise(self): number_of_plugins_before = len(plugin_pool.get_all_plugins()) # The first time we register the plugin is should work plugin_pool.register_plugin(DumbFixturePlugin) # Let's add it a second time. We should catch and exception raised = False try: plugin_pool.register_plugin(DumbFixturePlugin) except PluginAlreadyRegistered: raised = True self.assertTrue(raised) # Let's also unregister the plugin now, and assert it's not in the # pool anymore plugin_pool.unregister_plugin(DumbFixturePlugin) # Let's make sure we have the same number of plugins as before: number_of_plugins_after = len(plugin_pool.get_all_plugins()) self.assertEqual(number_of_plugins_before, number_of_plugins_after)
def get_widget(self, request, page, lang, name): """ Given the request and name of a placeholder return a PluginEditor Widget """ installed_plugins = plugin_pool.get_all_plugins(name) widget = PluginEditor(installed=installed_plugins) if not isinstance(widget(), Widget): widget = Textarea return widget
def get_queryset(self): range = self.request.GET.get("range") or None comparation = self.request.GET.get("comparation") or None keyword = self.request.GET.get("keyword") or None fields = self.request.GET.get("fields_search") or None plugins_found = self.lookingfor_plugins(keyword, plugin_pool.get_all_plugins()) plugins_filtered = self.filter_plugins(plugins_found, range, comparation, fields) return self.get_plugins_list(plugins_filtered)
def render_change_form(self, request, context, add=False, change=False, form_url="", obj=None): plugin = getattr(self, "cms_plugin_instance", None) if plugin: context.update( {"base_plugin": plugin, "installed_plugins": plugin_pool.get_all_plugins(plugin.placeholder.slot)} ) context["adminform"].form.initial.setdefault("plugins", plugin) return super(PhlogGalleryPlugin, self).render_change_form(request, context, add, change, form_url, obj)
def get_frontend_data_dict_for_placeholders(placeholders, request, editable=False): """ Takes a list of placeholder instances and returns the data that is used by the frontend to render all contents. The returned dict is grouped by placeholder slots. """ data_dict = {} for placeholder in placeholders: if placeholder: plugins = [] # We don't use the helper method `placeholder.get_plugins()` because of the wrong order by path. placeholder_plugins = placeholder.cmsplugin_set.filter(language=request.LANGUAGE_CODE).order_by( settings.DJANGOCMS_SPA_PLUGIN_ORDER_FIELD) for plugin in placeholder_plugins: # We need the complete cascading structure of the plugins in the frontend. This is why we ignore the # children here and add them later in the loop. if not plugin.parent: plugins.append(get_frontend_data_dict_for_plugin( request=request, plugin=plugin, editable=editable) ) if plugins or editable: data_dict[placeholder.slot] = { 'type': 'cmp-%s' % placeholder.slot, 'plugins': plugins, } if editable: # This is the structure of the template `cms/toolbar/placeholder.html` that is used to register # the frontend editing. from cms.plugin_pool import plugin_pool plugin_types = [cls.__name__ for cls in plugin_pool.get_all_plugins(placeholder.slot, placeholder.page)] allowed_plugins = plugin_types + plugin_pool.get_system_plugins() data_dict[placeholder.slot]['cms'] = [ 'cms-placeholder-{}'.format(placeholder.pk), { 'type': 'placeholder', 'name': str(placeholder.get_label()), 'page_language': request.LANGUAGE_CODE, 'placeholder_id': placeholder.pk, 'plugin_language': request.LANGUAGE_CODE, 'plugin_restriction': [module for module in allowed_plugins], 'addPluginHelpTitle': 'Add plugin to placeholder {}'.format(placeholder.get_label()), 'urls': { 'add_plugin': placeholder.get_add_url(), 'copy_plugin': placeholder.get_copy_url() } } ] return data_dict
def render_toolbar(self, request): from cms.plugin_pool import plugin_pool from cms.utils.admin import get_admin_menu_item_context """ Renders the Toolbar. """ auth = request.user.is_staff or request.user.is_superuser edit = request.session.get('cms_edit', False) and auth page = request.current_page move_dict = [] if edit and page: template = get_template_from_request(request) placeholders = get_placeholders(template) for placeholder in placeholders: d = {} name = cms_settings.CMS_PLACEHOLDER_CONF.get( "%s %s" % (page.get_template(), placeholder), {}).get("name", None) if not name: name = cms_settings.CMS_PLACEHOLDER_CONF.get( placeholder, {}).get("name", None) if not name: name = title(placeholder) else: name = _(name) d['name'] = name plugins = plugin_pool.get_all_plugins(placeholder, page) d['plugins'] = [] for p in plugins: d['plugins'].append(p.value) d['type'] = placeholder move_dict.append(d) data = safe(simplejson.dumps(move_dict)) else: data = {} if auth and page: context = get_admin_menu_item_context(request, page, filtered=False) else: context = {} context.update({ 'auth': auth, 'page': page, 'templates': cms_settings.CMS_TEMPLATES, 'auth_error': not auth and 'cms_username' in request.POST, 'placeholder_data': data, 'edit': edit, 'moderator': cms_settings.CMS_MODERATOR, 'CMS_MEDIA_URL': cms_settings.CMS_MEDIA_URL, }) #from django.core.context_processors import csrf #context.update(csrf(request)) return render_to_string('cms/toolbar/toolbar.html', context, RequestContext(request))
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): plugin = getattr(self, 'cms_plugin_instance', None) if plugin: context.update({ 'base_plugin': plugin, 'installed_plugins': plugin_pool.get_all_plugins(plugin.placeholder.slot) }) context['adminform'].form.initial.setdefault('plugins', plugin) return super(PhlogGalleryPlugin, self).render_change_form(request, context, add, change, form_url, obj)
def _child_classes(self): """All registered plugins shall be allowed as children for this plugin""" if getattr(self, '_cached_child_classes', None) is not None: return self._cached_child_classes self._cached_child_classes = list(getattr(self, 'generic_child_classes', [])) or [] for p in plugin_pool.get_all_plugins(): if (isinstance(p.parent_classes, (list, tuple)) and self.__class__.__name__ in p.parent_classes and p.__name__ not in self._cached_child_classes): self._cached_child_classes.append(p.__name__) return self._cached_child_classes
def handle_label(self, label, **options): plugin_pool.get_all_plugins() queryset = CMSPlugin.objects.filter(plugin_type=label) number_of_plugins = queryset.count() if number_of_plugins > 0: if options.get('interactive'): confirm = input(""" You have requested to remove %d %r plugins. Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """ % (number_of_plugins, label)) else: confirm = 'yes' if confirm == 'yes': queryset.delete() self.stdout.write('%d %r plugins uninstalled\n' % (number_of_plugins, label)) else: self.stdout.write('Aborted') else: self.stdout.write('no %r plugins found\n' % label)
def _get_cascade_elements(cls): """ Returns a set of models which are derived from ``CascadeModelBase``. This set shall be used for traversing the plugin tree of interconnected Cascade models. Currently, Cascade itself offers only one model, namely ``CascadeElement``, but a third party library may extend ``CascadeModelBase`` and add arbitrary model fields. """ if not hasattr(cls, "_cached_cascade_elements"): cce = set([p.model._meta.concrete_model for p in plugin_pool.get_all_plugins() if issubclass(p.model, cls)]) cls._cached_cascade_elements = cce return cls._cached_cascade_elements
def get_child_classes(self, slot, page): template = page and page.get_template() or None # config overrides.. ph_conf = get_placeholder_conf('child_classes', slot, template, default={}) child_classes = ph_conf.get(self.__class__.__name__, self.child_classes) if child_classes: return child_classes from cms.plugin_pool import plugin_pool installed_plugins = plugin_pool.get_all_plugins(slot, page) return [cls.__name__ for cls in installed_plugins]
def _get_cascade_elements(cls): """ Returns a set of models which are derived from CascadeModelBase. This set shall be used for traversing the plugin tree, since children can be interconnected using different plugins. """ if not hasattr(cls, '_cached_cascade_elements'): cce = set([p.model._meta.concrete_model for p in plugin_pool.get_all_plugins() if issubclass(p.model, cls)]) setattr(cls, '_cached_cascade_elements', cce) return cls._cached_cascade_elements
def test_get_all_plugins_single_page(self): page = create_page("page", "col_two.html", "en") placeholder = page.placeholders.get(slot="col_left") conf = { "col_two": {"plugins": ["TextPlugin", "LinkPlugin"]}, "col_two.html col_left": {"plugins": ["LinkPlugin"]}, } with SettingsOverride(CMS_PLACEHOLDER_CONF=conf): plugins = plugin_pool.get_all_plugins(placeholder, page) self.assertEqual(len(plugins), 1, plugins) self.assertEqual(plugins[0], LinkPlugin)
def plugins_for_site(self): if not hasattr(self, '_plugins_for_site'): cascade_plugins = set([ p for p in plugin_pool.get_all_plugins() if issubclass(p, ExtraFieldsMixin) ]) self._plugins_for_site = [(p.__name__, '{} {}'.format(p.module, force_text(p.name))) for p in cascade_plugins] return self._plugins_for_site
def handle_label(self, label, **options): plugin_pool.get_all_plugins() queryset = CMSPlugin.objects.filter(plugin_type=label) number_of_plugins = queryset.count() if number_of_plugins > 0: if options.get('interactive'): confirm = raw_input(""" You have requested to remove %d %r plugins. Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """ % (number_of_plugins, label)) else: confirm = 'yes' if confirm == 'yes': queryset.delete() self.stdout.write(u'%d %r plugins uninstalled\n' % (number_of_plugins, label)) else: self.stdout.write(u'Aborted') else: self.stdout.write(u'no %r plugins found\n' % label)
def render_extra_menu_items(context, obj, template='cms/toolbar/dragitem_extra_menu.html'): request = context['request'] toolbar = getattr(request, 'toolbar', None) if toolbar: template = toolbar.get_cached_template(template) else: template = context.template.engine.get_template(template) if isinstance(obj, CMSPlugin): plugin = obj plugin_class_inst = plugin.get_plugin_class_instance() items = plugin_class_inst.get_extra_local_plugin_menu_items( request, plugin) or [] plugin_classes = plugin_pool.get_all_plugins() for plugin_class in plugin_classes: plugin_items = plugin_class().get_extra_global_plugin_menu_items( request, plugin) if plugin_items: items.extend(plugin_items) elif isinstance(obj, PlaceholderModel): items = [] plugin_classes = plugin_pool.get_all_plugins() for plugin_class in plugin_classes: plugin_class_inst = plugin_class() plugin_items = plugin_class_inst.get_extra_placeholder_menu_items( request, obj) if plugin_items: items.extend(plugin_items) else: items = [] if not items: return '' return template.render(Context({'items': items}))
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 # Builds the list of dictionaries containing module, name and value for the plugin dropdowns installed_plugins = get_toolbar_plugin_struct( plugin_pool.get_all_plugins(slot, page), slot, page) name = get_placeholder_conf("name", slot, template, title(slot)) name = _(name) context.push() context['installed_plugins'] = installed_plugins ## to restrict child-only plugins from draggables.. context['allowed_plugins'] = [ cls.__name__ for cls in plugin_pool.get_all_plugins(slot, page) ] context['language'] = get_language_from_request(request) context['placeholder_label'] = name context['placeholder'] = placeholder context['page'] = page toolbar = render_to_string("cms/toolbar/placeholder_bar.html", context) context.pop() return toolbar
def test_plugin_is_tested(self): """ Runs over the general Plugin list in the settings and makes sure, all those plugins are tested here. """ plugin_list = [i[0] for i in self.plugin_list] all_plugin_list = [str(i.value) for i in plugin_pool.get_all_plugins()] for plugin in all_plugin_list: if (not plugin in self.plugin_exclude_list and not plugin in plugin_list): print(f'WRN: {plugin} is not tested.')
def plugins_for_site(self): def show_in_backend(plugin): try: config = app_settings.CMSPLUGIN_CASCADE['plugins_with_extra_fields'][plugin.__name__] except KeyError: return False else: assert issubclass(plugin, ExtraFieldsMixin) return config.allow_override cascade_plugins = set([p for p in plugin_pool.get_all_plugins() if show_in_backend(p)]) return [(p.__name__, '{}: {}'.format(p.module, force_text(p.name))) for p in cascade_plugins]
def get_parent_classes(self, slot, page): template = page and page.get_template() or None ph_conf = get_placeholder_conf('parent_classes', slot, template, default={}) parent_classes = ph_conf.get(self.__class__.__name__, self.parent_classes) if parent_classes is None: return # allow all parent classes which inherit from TransparentMixin parent_classes = set(parent_classes) for p in plugin_pool.get_all_plugins(): if self.allow_children and issubclass(p, TransparentMixin): parent_classes.add(p.__name__) return tuple(parent_classes)
def get_child_classes(self, slot, page): if isinstance(self.child_classes, (list, tuple)): return self.child_classes # otherwise determine child_classes by evaluating parent_classes from other plugins child_classes = set() for p in plugin_pool.get_all_plugins(): if (isinstance(p.parent_classes, (list, tuple)) and self.__class__.__name__ in p.parent_classes or p.parent_classes is None and issubclass(p, CascadePluginBase) or isinstance(self.alien_child_classes, (list, tuple)) and p.__name__ in self.alien_child_classes or self.alien_child_classes is True and p.__name__ in settings.CMSPLUGIN_CASCADE['alien_plugins']): child_classes.add(p.__name__) return tuple(child_classes)
def _child_classes(self): """All registered plugins shall be allowed as children for this plugin""" if getattr(self, '_cached_child_classes', None) is not None: return self._cached_child_classes self._cached_child_classes = list( getattr(self, 'generic_child_classes', [])) or [] for p in plugin_pool.get_all_plugins(): if (isinstance(p.parent_classes, (list, tuple)) and self.__class__.__name__ in p.parent_classes and p.__name__ not in self._cached_child_classes): self._cached_child_classes.append(p.__name__) return self._cached_child_classes
def get_plugins(): from cms.plugin_pool import plugin_pool global _leaf_transparent_plugins try: return _leaf_transparent_plugins except NameError: _leaf_transparent_plugins = [ plugin.__name__ for plugin in plugin_pool.get_all_plugins() if issubclass(plugin, TransparentContainer) ] return _leaf_transparent_plugins