예제 #1
0
    def __call__(self):
        pc = api.portal.get_tool('portal_catalog')
        brains = pc.searchResults(portal_type='Snippet',
                                  sort_on='getObjPositionInParent')

        user_pantry = []
        for brain in brains:
            user_pantry.append(
                dict(title=brain.Title,
                     description=brain.Description,
                     url='{0}/raw'.format(brain.getURL())))

        theme_pantry = []
        if isThemeEnabled(self.request):
            currentTheme = getCurrentTheme()
            if currentTheme is not None:
                themeDirectory = queryResourceDirectory(
                    THEME_RESOURCE_NAME, currentTheme)
                if themeDirectory is not None:
                    if themeDirectory.isDirectory(PANTRY_DIRECTORY):
                        theme_pantry = self.get_theme_pantry(themeDirectory)

        if theme_pantry:
            pantry = user_pantry + theme_pantry
        else:
            pantry = user_pantry
        self.request.response.setHeader('Content-Type', 'application/json')
        return json.dumps(pantry, indent=2, sort_keys=True)
예제 #2
0
    def setupTransform(self, runtrace=False):
        request = self.request
        DevelopmentMode = self.develop_theme()

        # Obtain settings. Do nothing if not found
        settings = self.getSettings()

        if settings is None:
            return None

        if not isThemeEnabled(request, settings):
            return None

        cache = getCache(settings)

        # Apply theme
        transform = None

        if not DevelopmentMode:
            transform = cache.transform

        if transform is None:
            rules = settings.rules
            absolutePrefix = settings.absolutePrefix or None
            readNetwork = settings.readNetwork
            parameterExpressions = settings.parameterExpressions

            transform = compileThemeTransform(rules, absolutePrefix, readNetwork, parameterExpressions, runtrace=runtrace)
            if transform is None:
                return None
            
            if not DevelopmentMode:
                cache.updateTransform(transform)

        return transform
예제 #3
0
    def setupTransform(self, runtrace=False):
        request = self.request
        DevelopmentMode = Globals.DevelopmentMode

        # Obtain settings. Do nothing if not found
        settings = self.getSettings()

        if settings is None:
            return None

        if not isThemeEnabled(request, settings):
            return None

        cache = getCache(settings)

        # Apply theme
        transform = None

        if not DevelopmentMode:
            transform = cache.transform

        if transform is None:
            rules = settings.rules
            absolutePrefix = settings.absolutePrefix or None
            readNetwork = settings.readNetwork
            parameterExpressions = settings.parameterExpressions

            transform = compileThemeTransform(rules, absolutePrefix, readNetwork, parameterExpressions, runtrace=runtrace)
            if transform is None:
                return None

            if not DevelopmentMode:
                cache.updateTransform(transform)

        return transform
예제 #4
0
def getFragmentSchemata(name):
    """Get matching XML schema for theme fragment"""
    request = getRequest()
    filename = (u'{0:s}.xml'.format(name)).encode('utf-8', 'ignore')

    if not isThemeEnabled(request):
        return SimpleVocabulary([])

    currentTheme = getCurrentTheme()
    if currentTheme is None:
        return SimpleVocabulary([])

    themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme)
    if themeDirectory is None:
        return SimpleVocabulary([])

    if not themeDirectory.isDirectory(FRAGMENTS_DIRECTORY):
        return SimpleVocabulary([])

    if not themeDirectory[FRAGMENTS_DIRECTORY].isFile(filename):
        return ()

    handle = themeDirectory[FRAGMENTS_DIRECTORY].openFile(filename)
    schemata = parse(handle, 'collective.themefragments').schemata.values()
    for schema_ in schemata:
        schema_.__name__ = schema_.__name__.encode('utf-8', 'ignore')
    return schemata
예제 #5
0
    def __call__(self, context=None):
        request = getRequest()

        if not isThemeEnabled(request):
            return SimpleVocabulary([])

        currentTheme = getCurrentTheme()
        if currentTheme is None:
            return SimpleVocabulary([])

        themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme)  # noqa
        if themeDirectory is None:
            return SimpleVocabulary([])

        if not themeDirectory.isDirectory(FRAGMENTS_DIRECTORY):
            return SimpleVocabulary([])

        # Get settings to map titles
        titles = getFragmentsSettings(themeDirectory, 'themefragments:tiles')

        tiles = [splitext(filename)[0] for filename
                 in themeDirectory[FRAGMENTS_DIRECTORY].listDirectory()
                 if splitext(filename)[-1] == '.pt' and
                 themeDirectory[FRAGMENTS_DIRECTORY].isFile(filename)]

        terms = [SimpleTerm(None, '', _(u'-- select fragment --'))]
        for tile in tiles:
            title = titles.get(tile, None)
            title = title is None and tile or title.strip().split('#')[0]
            if title:
                terms.append(SimpleTerm(tile, tile, title))
        return SimpleVocabulary(terms)
    def __getitem__(self, name):
        # Make sure a theme is enabled
        if not isThemeEnabled(self.request):
            raise KeyError(name)

        # Check if there is views/<name>.pt in the theme, if not raise
        currentTheme = getCurrentTheme()
        if currentTheme is None:
            raise KeyError(name)

        themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme)  # noqa
        if themeDirectory is None:
            raise KeyError(name)

        templatePath = "%s/%s.pt" % (FRAGMENTS_DIRECTORY, name,)
        if not themeDirectory.isFile(templatePath):
            raise KeyError(name)

        try:
            owner = themeDirectory[templatePath].getOwner()
        except AttributeError:
            owner = getSite().getOwner()
        template = themeDirectory.readFile(templatePath).decode('utf-8', 'replace')  # noqa

        # Now disable the theme so we don't double-transform
        if self._disable_theming:
            self.request.response.setHeader('X-Theme-Disabled', '1')

        # Get settings to map fragment permissions
        permission = getFragmentsSettings(
            themeDirectory, 'themefragments:permissions').get(name) or 'zope.Public'  # noqa

        return FragmentView(self.context, self.request, name, permission, template, owner)  # noqa
예제 #7
0
def getFragmentSchemata(name):
    """Get matching XML schema for theme fragment"""
    request = getRequest()
    filename = (u'{0:s}.xml'.format(name)).encode('utf-8', 'ignore')

    if not isThemeEnabled(request):
        return SimpleVocabulary([])

    currentTheme = getCurrentTheme()
    if currentTheme is None:
        return SimpleVocabulary([])

    themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme)
    if themeDirectory is None:
        return SimpleVocabulary([])

    if not themeDirectory.isDirectory(FRAGMENTS_DIRECTORY):
        return SimpleVocabulary([])

    if not themeDirectory[FRAGMENTS_DIRECTORY].isFile(filename):
        return ()

    handle = themeDirectory[FRAGMENTS_DIRECTORY].openFile(filename)
    schemata = parse(handle, 'collective.themefragments').schemata.values()
    for schema_ in schemata:
        schema_.__name__ = schema_.__name__.encode('utf-8', 'ignore')
    return schemata
예제 #8
0
    def __call__(self, context=None):
        request = getRequest()

        if not isThemeEnabled(request):
            return SimpleVocabulary([])

        currentTheme = getCurrentTheme()
        if currentTheme is None:
            return SimpleVocabulary([])

        themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME,
                                                currentTheme)  # noqa
        if themeDirectory is None:
            return SimpleVocabulary([])

        if not themeDirectory.isDirectory(FRAGMENTS_DIRECTORY):
            return SimpleVocabulary([])

        # Get settings to map titles
        titles = getFragmentsSettings(themeDirectory, 'themefragments:tiles')

        tiles = [
            splitext(filename)[0] for filename in
            themeDirectory[FRAGMENTS_DIRECTORY].listDirectory()
            if splitext(filename)[-1] == '.pt'
            and themeDirectory[FRAGMENTS_DIRECTORY].isFile(filename)
        ]

        terms = [SimpleTerm(None, '', _(u'-- select fragment --'))]
        for tile in tiles:
            title = titles.get(tile, None)
            title = title is None and tile or title.strip().split('#')[0]
            if title and not title.startswith("Hidden"):
                terms.append(SimpleTerm(tile, tile, title))
        return SimpleVocabulary(terms)
예제 #9
0
def getFragmentSchemata(name):
    """Get matching XML schema for theme fragment"""
    request = getRequest()
    filename = '{0}.xml'.format(name)

    if not isThemeEnabled(request):
        return SimpleVocabulary([])

    currentTheme = getCurrentTheme()
    if currentTheme is None:
        return SimpleVocabulary([])

    themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme)
    if themeDirectory is None:
        return SimpleVocabulary([])

    if not themeDirectory.isDirectory(FRAGMENTS_DIRECTORY):
        return SimpleVocabulary([])

    if not themeDirectory[FRAGMENTS_DIRECTORY].isFile(filename):
        return ()

    with themeDirectory[FRAGMENTS_DIRECTORY].openFile(filename) as handle:
        schemata = parse(handle, 'collective.themefragments').schemata.values()

    return schemata
예제 #10
0
def setHeader(object, event):
    """Set a header X-Theme-Enabled in the request if theming is enabled.

    This is useful for checking in things like the portal_css/portal_
    javascripts registries.
    """

    request = event.request

    if isThemeEnabled(request):
        request.environ['HTTP_X_THEME_ENABLED'] = True
예제 #11
0
    def test_isThemeEnabled_blacklist(self):
        from zope.component import getUtility

        from plone.registry.interfaces import IRegistry

        from plone.app.theming.interfaces import IThemeSettings
        from plone.app.theming.utils import isThemeEnabled

        settings = getUtility(IRegistry).forInterface(IThemeSettings, False)
        settings.enabled = True
        settings.rules = u"/++theme++foo/rules.xml"

        request = self.layer["request"]
        request.set("BASE1", "http://nohost/path/to/site")

        self.assertTrue(isThemeEnabled(request, settings))
        self.assertEqual(request.get("SERVER_URL"), "http://nohost")

        # Should pay no attention to BASE1 and only use SERVER_URL
        settings.hostnameBlacklist.append("nohost")
        self.assertFalse(isThemeEnabled(request, settings))
예제 #12
0
    def test_isThemeEnabled_blacklist(self):
        from zope.component import getUtility

        from plone.registry.interfaces import IRegistry

        from plone.app.theming.interfaces import IThemeSettings
        from plone.app.theming.utils import isThemeEnabled

        settings = getUtility(IRegistry).forInterface(IThemeSettings, False)
        settings.enabled = True
        settings.rules = u"/++theme++foo/rules.xml"

        request = self.layer['request']
        request.set('BASE1', 'http://nohost/path/to/site')

        self.assertTrue(isThemeEnabled(request, settings))
        self.assertEqual(request.get('SERVER_URL'), 'http://nohost')

        # Should pay no attention to BASE1 and only use SERVER_URL
        settings.hostnameBlacklist.append('nohost')
        self.assertFalse(isThemeEnabled(request, settings))
예제 #13
0
 def get_cooked_bundles(self):
     """
     Get the cooked bundles
     """
     cache = component.queryUtility(ram.IRAMCache)
     bundles = self.get_bundles()
     # Check if its Diazo enabled
     if isThemeEnabled(self.request):
         theme = getCurrentTheme()
         themeObj = getTheme(theme)
         enabled_diazo_bundles = themeObj.enabled_bundles
         disabled_diazo_bundles = themeObj.disabled_bundles
         if hasattr(themeObj, 'production_css'):
             self.diazo_production_css = themeObj.production_css
             self.diazo_development_css = themeObj.development_css
             self.diazo_development_js = themeObj.development_js
             self.diazo_production_js = themeObj.production_js
         else:
             self.diazo_production_css = None
             self.diazo_development_css = None
             self.diazo_development_js = None
             self.diazo_production_js = None
     else:
         enabled_diazo_bundles = []
         disabled_diazo_bundles = []
         self.diazo_production_css = None
         self.diazo_development_css = None
         self.diazo_development_js = None
         self.diazo_production_js = None
     for key, bundle in bundles.items():
         # The diazo manifest is more important than the disabled bundle on registry
         # We can access the site with diazo.off=1 without diazo bundles
         if (bundle.enabled or key in enabled_diazo_bundles) and (key not in disabled_diazo_bundles):
             # check expression
             if bundle.expression:
                 cooked_expression = None
                 if cache is not None:
                     cooked_expression = cache.query(
                         'plone.bundles.cooked_expressions',
                         key=dict(prefix=bundle.__prefix__), default=None)
                 if (
                         cooked_expression is None or
                         cooked_expression.text != bundle.expression):
                     cooked_expression = Expression(bundle.expression)
                     if cache is not None:
                         cache.set(
                             cooked_expression,
                             'plone.bundles.cooked_expressions',
                             key=dict(prefix=bundle.__prefix__))
                 if not self.evaluateExpression(
                         cooked_expression, self.context):
                     continue
             yield key, bundle
예제 #14
0
    def get_theme_pantry(self):
        theme_pantry = []
        if isThemeEnabled(self.request):
            currentTheme = getCurrentTheme()
            if currentTheme is not None:
                themeDirectory = queryResourceDirectory(
                    THEME_RESOURCE_NAME, currentTheme)
                if themeDirectory is not None:
                    if themeDirectory.isDirectory(PANTRY_DIRECTORY):
                        theme_pantry = self.get_theme_pantry_info(
                            themeDirectory)

        return theme_pantry
예제 #15
0
    def test_isThemeEnabled(self):
        from zope.component import getUtility

        from plone.registry.interfaces import IRegistry

        from plone.app.theming.interfaces import IThemeSettings
        from plone.app.theming.utils import isThemeEnabled

        settings = getUtility(IRegistry).forInterface(IThemeSettings, False)
        settings.enabled = True
        settings.rules = u"/++theme++foo/rules.xml"

        request = self.layer["request"]

        self.assertTrue(isThemeEnabled(request, settings))
예제 #16
0
    def test_isThemeEnabled(self):
        from zope.component import getUtility

        from plone.registry.interfaces import IRegistry

        from plone.app.theming.interfaces import IThemeSettings
        from plone.app.theming.utils import isThemeEnabled

        settings = getUtility(IRegistry).forInterface(IThemeSettings, False)
        settings.enabled = True
        settings.rules = u"/++theme++foo/rules.xml"

        request = self.layer['request']

        self.assertTrue(isThemeEnabled(request, settings))
예제 #17
0
 def get_theme(self):
     # Volatile attribute to cache the current theme
     if hasattr(self.portal, '_v_currentTheme'):
         themeObj = self.portal._v_currentTheme
     else:
         theme = getCurrentTheme()
         themeObj = getTheme(theme)
         self.portal._v_currentTheme = themeObj
     cache = component.queryUtility(ram.IRAMCache)
     if isThemeEnabled(self.request):
         themeObj = cache.query('plone.currentTheme',
                                key=dict(prefix='theme'),
                                default=None)
         if themeObj is None:
             theme = getCurrentTheme()
             themeObj = getTheme(theme)
             cache.set(themeObj,
                       'plone.currentTheme',
                       key=dict(prefix='theme'))
     return themeObj
    def __getitem__(self, name):
        # Make sure a theme is enabled
        if not isThemeEnabled(self.request):
            raise KeyError(name)

        # Check if there is views/<name>.pt in the theme, if not raise
        currentTheme = getCurrentTheme()
        if currentTheme is None:
            raise KeyError(name)

        themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME,
                                                currentTheme)  # noqa
        if themeDirectory is None:
            raise KeyError(name)

        templatePath = "%s/%s.pt" % (
            FRAGMENTS_DIRECTORY,
            name,
        )
        if not themeDirectory.isFile(templatePath):
            raise KeyError(name)

        try:
            owner = themeDirectory[templatePath].getOwner()
        except AttributeError:
            owner = getSite().getOwner()
        template = themeDirectory.readFile(templatePath).decode(
            'utf-8', 'replace')  # noqa

        # Now disable the theme so we don't double-transform
        if self._disable_theming:
            self.request.response.setHeader('X-Theme-Disabled', '1')

        # Get settings to map fragment permissions
        permission = getFragmentsSettings(
            themeDirectory,
            'themefragments:permissions').get(name) or 'zope.Public'  # noqa

        return FragmentView(self.context, self.request, name, permission,
                            template, owner)  # noqa
예제 #19
0
def onRequest(object, event):
    """Call onRequest() on each plugin for the eanbled theme on each request
    """

    request = event.request

    if not isThemeEnabled(request):
        return

    theme = getCurrentTheme()
    if theme is None:
        return

    themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, theme)
    if themeDirectory is None:
        return

    plugins = getPlugins()
    pluginSettings = getPluginSettings(themeDirectory, plugins)

    for name, plugin in plugins:
        plugin.onRequest(request, theme, pluginSettings[name], pluginSettings)
예제 #20
0
 def get_theme(self):
     # Volatile attribute to cache the current theme
     if hasattr(self.portal, '_v_currentTheme'):
         themeObj = self.portal._v_currentTheme
     else:
         theme = getCurrentTheme()
         themeObj = getTheme(theme)
         self.portal._v_currentTheme = themeObj
     cache = component.queryUtility(ram.IRAMCache)
     if isThemeEnabled(self.request):
         themeObj = cache.query(
             'plone.currentTheme',
             key=dict(prefix='theme'),
             default=None)
         if themeObj is None:
             theme = getCurrentTheme()
             themeObj = getTheme(theme)
             cache.set(
                 themeObj,
                 'plone.currentTheme',
                 key=dict(prefix='theme'))
     return themeObj
예제 #21
0
파일: hooks.py 프로젝트: CGTIC/Plone_SP
def onRequest(object, event):
    """Call onRequest() on each plugin for the eanbled theme on each request
    """

    request = event.request

    if not isThemeEnabled(request):
        return

    theme = getCurrentTheme()
    if theme is None:
        return

    themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, theme)
    if themeDirectory is None:
        return

    plugins = getPlugins()
    pluginSettings = getPluginSettings(themeDirectory, plugins)

    for name, plugin in plugins:
        plugin.onRequest(request, theme, pluginSettings[name], pluginSettings)
예제 #22
0
    def __call__(self, context=None):
        request = getRequest()

        if not isThemeEnabled(request):
            return SimpleVocabulary([])

        currentTheme = getCurrentTheme()
        if currentTheme is None:
            return SimpleVocabulary([])

        themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme)  # noqa
        if themeDirectory is None:
            return SimpleVocabulary([])

        if not themeDirectory.isDirectory(FRAGMENTS_DIRECTORY):
            return SimpleVocabulary([])

        # Get settings to map titles
        titles = getFragmentsSettings(themeDirectory, 'themefragments:tiles')

        tiles = [splitext(filename)[0] for filename
                 in themeDirectory[FRAGMENTS_DIRECTORY].listDirectory()
                 if splitext(filename)[-1] == '.pt' and
                 themeDirectory[FRAGMENTS_DIRECTORY].isFile(filename)]

        fragment_tiles = []
        for tile in tiles:
            title = titles.get(tile, None)
            title = title is None and tile or title.strip().split('#')[0]
            if title and not title.startswith("Hidden"):
                fragment_tiles.append([title, tile])

        fragment_tiles.append([_(u'-- select fragment --'), None ])
        fragment_tiles.sort()
        terms = [ SimpleTerm(value=pair[1], token=pair[1], title=pair[0]) for pair in fragment_tiles ]
        return SimpleVocabulary(terms)
예제 #23
0
    def setupTransform(self):
        request = self.request
        DevelopmentMode = Globals.DevelopmentMode

        # Obtain settings. Do nothing if not found
        toadapt = (getSite(), self.request)
        settings = getMultiAdapter(toadapt, IThemeSettings)

        if settings is None:
            return None

        if not isThemeEnabled(request, settings):
            return None

        cache = getCache(settings)

        # Apply theme
        transform = None

        if not DevelopmentMode:
            transform = cache.transform

        if transform is None:
            rules = settings.rules
            absolutePrefix = settings.absolutePrefix or None
            readNetwork = settings.readNetwork
            accessControl = etree.XSLTAccessControl(read_file=True, write_file=False, create_dir=False, read_network=readNetwork, write_network=False)

            if absolutePrefix:
                absolutePrefix = expandAbsolutePrefix(absolutePrefix)

            params = set(settings.parameterExpressions.keys() + ['url', 'base', 'path', 'scheme', 'host'])
            xslParams = dict((k, '') for k in params)

            internalResolver = InternalResolver()
            pythonResolver = PythonResolver()
            if readNetwork:
                networkResolver = NetworkResolver()

            rulesParser = etree.XMLParser(recover=False)
            rulesParser.resolvers.add(internalResolver)
            rulesParser.resolvers.add(pythonResolver)
            if readNetwork:
                rulesParser.resolvers.add(networkResolver)

            themeParser = etree.HTMLParser()
            themeParser.resolvers.add(internalResolver)
            themeParser.resolvers.add(pythonResolver)
            if readNetwork:
                themeParser.resolvers.add(networkResolver)

            compilerParser = etree.XMLParser()
            compilerParser.resolvers.add(internalResolver)
            compilerParser.resolvers.add(pythonResolver)
            if readNetwork:
                compilerParser.resolvers.add(networkResolver)

            compiledTheme = compile_theme(rules,
                    absolute_prefix=absolutePrefix,
                    parser=themeParser,
                    rules_parser=rulesParser,
                    compiler_parser=compilerParser,
                    read_network=readNetwork,
                    access_control=accessControl,
                    update=True,
                    xsl_params=xslParams,
                )

            if not compiledTheme:
                return None

            transform = etree.XSLT(compiledTheme,
                    access_control=accessControl,
                )

            if not DevelopmentMode:
                cache.updateTransform(transform)

        return transform
예제 #24
0
 def isThemeEnabled(self):
     return isThemeEnabled(self.request)
예제 #25
0
 def test_theme_enabled(self):
     from plone.app.theming.utils import isThemeEnabled
     self.assertTrue(isThemeEnabled(self.request))
예제 #26
0
    def transformIterable(self, result, encoding):
        """Apply the transform if required
        """
        # Obtain settings. Do nothing if not found
        settings = self.getSettings()
        if settings is None:
            return None
        if not isThemeEnabled(self.request, settings):
            return None
        result = self.parseTree(result)
        if result is None:
            return None

        DevelopmentMode = Globals.DevelopmentMode
        diazo_debug = self.request.get('diazo.debug', '').lower()
        runtrace = (
            DevelopmentMode
            and diazo_debug in ('1', 'y', 'yes', 't', 'true')
        )

        try:
            etree.clear_error_log()

            if settings.doctype:
                result.doctype = settings.doctype
                if not result.doctype.endswith('\n'):
                    result.doctype += '\n'

            transform = self.setupTransform(runtrace=runtrace)
            if transform is None:
                return None

            cache = None
            if not DevelopmentMode:
                cache = getCache(settings)

            parameterExpressions = settings.parameterExpressions or {}
            params = prepareThemeParameters(
                findContext(self.request),
                self.request,
                parameterExpressions,
                cache
            )

            transformed = transform(result.tree, **params)
            error_log = transform.error_log
            if transformed is not None:
                # Transformed worked, swap content with result
                result.tree = transformed
        except etree.LxmlError as e:
            if not(DevelopmentMode):
                raise
            error_log = e.error_log
            runtrace = True

        if runtrace:
            from diazo.runtrace import generate_debug_html
            # Add debug information to end of body
            body = result.tree.xpath('/html/body')[0]
            debug_url = findContext(
                self.request
            ).portal_url() + '/++resource++diazo-debug'
            body.insert(
                -1,
                generate_debug_html(
                    debug_url,
                    rules=settings.rules,
                    rules_parser=getParser('rules', settings.readNetwork),
                    error_log=error_log,
                )
            )
        return result
예제 #27
0
    def get_cooked_bundles(self):
        """
        Get the cooked bundles
        """
        cache = component.queryUtility(ram.IRAMCache)
        bundles = self.get_bundles()
        # Check if its Diazo enabled
        if isThemeEnabled(self.request):
            portal = self.portal_state.portal()
            # Volatile attribute to cache the current theme
            if hasattr(portal, '_v_currentTheme'):
                themeObj = portal._v_currentTheme
            else:
                theme = getCurrentTheme()
                themeObj = getTheme(theme)
                portal._v_currentTheme = themeObj
            enabled_diazo_bundles = themeObj.enabled_bundles
            disabled_diazo_bundles = themeObj.disabled_bundles
            if hasattr(themeObj, 'production_css'):
                self.diazo_production_css = themeObj.production_css
                self.diazo_development_css = themeObj.development_css
                self.diazo_development_js = themeObj.development_js
                self.diazo_production_js = themeObj.production_js
            else:
                self.diazo_production_css = None
                self.diazo_development_css = None
                self.diazo_development_js = None
                self.diazo_production_js = None
        else:
            enabled_diazo_bundles = []
            disabled_diazo_bundles = []
            self.diazo_production_css = None
            self.diazo_development_css = None
            self.diazo_development_js = None
            self.diazo_production_js = None

        # Request set bundles
        enabled_request_bundles = []
        disabled_request_bundles = []
        if hasattr(self.request, 'enabled_bundles'):
            enabled_request_bundles.extend(self.request.enabled_bundles)

        if hasattr(self.request, 'disabled_bundles'):
            disabled_request_bundles.extend(self.request.disabled_bundles)

        for key, bundle in bundles.items():
            # The diazo manifest and request bundles are more important than
            # the disabled bundle on registry.
            # We can access the site with diazo.off=1 without diazo bundles
            if (bundle.enabled
                    or key in enabled_request_bundles
                    or key in enabled_diazo_bundles) and\
                    (key not in disabled_diazo_bundles
                        and key not in disabled_request_bundles):
                # check expression
                if bundle.expression:
                    cooked_expression = None
                    if cache is not None:
                        cooked_expression = cache.query(
                            'plone.bundles.cooked_expressions',
                            key=dict(prefix=bundle.__prefix__),
                            default=None)
                    if (cooked_expression is None
                            or cooked_expression.text != bundle.expression):
                        cooked_expression = Expression(bundle.expression)
                        if cache is not None:
                            cache.set(cooked_expression,
                                      'plone.bundles.cooked_expressions',
                                      key=dict(prefix=bundle.__prefix__))
                    if not self.evaluateExpression(cooked_expression,
                                                   self.context):
                        continue
                yield key, bundle
예제 #28
0
    def transformIterable(self, result, encoding):
        """Apply the transform if required
        """
        # Obtain settings. Do nothing if not found
        settings = self.getSettings()
        if settings is None:
            return None
        if not isThemeEnabled(self.request, settings):
            return None
        result = self.parseTree(result)
        if result is None:
            return None

        DevelopmentMode = Globals.DevelopmentMode
        diazo_debug = self.request.get("diazo.debug", "").lower()
        runtrace = DevelopmentMode and diazo_debug in ("1", "y", "yes", "t", "true")

        try:
            etree.clear_error_log()

            if settings.doctype:
                result.doctype = settings.doctype
                if not result.doctype.endswith("\n"):
                    result.doctype += "\n"

            transform = self.setupTransform(runtrace=runtrace)
            if transform is None:
                return None

            cache = None
            if not DevelopmentMode:
                cache = getCache(settings)

            parameterExpressions = settings.parameterExpressions or {}
            params = prepareThemeParameters(findContext(self.request), self.request, parameterExpressions, cache)

            transformed = transform(result.tree, **params)
            error_log = transform.error_log
            if transformed is not None:
                # Transformed worked, swap content with result
                result.tree = transformed
        except etree.LxmlError as e:
            if not (DevelopmentMode):
                raise
            error_log = e.error_log
            runtrace = True

        if runtrace:
            from diazo.runtrace import generate_debug_html

            # Add debug information to end of body
            body = result.tree.xpath("/html/body")[0]
            debug_url = findContext(self.request).portal_url() + "/++resource++diazo-debug"
            body.insert(
                -1,
                generate_debug_html(
                    debug_url,
                    rules=settings.rules,
                    rules_parser=getParser("rules", settings.readNetwork),
                    error_log=error_log,
                ),
            )
        return result
예제 #29
0
    def tinymce(self):
        """
        data-pat-tinymce : JSON.stringify({
            relatedItems: {
              vocabularyUrl: config.portal_url +
                '/@@getVocabulary?name=plone.app.vocabularies.Catalog'
            },
            rel_upload_path: '@@fileUpload',
            folder_url: config.document_base_url,
            tiny: config,
            prependToUrl: 'resolveuid/',
            linkAttribute: 'UID',
            prependToScalePart: '/@@images/image/'
          })
        """
        registry = getUtility(IRegistry)
        settings = registry.forInterface(ITinyMCESchema, prefix="plone")
        config = {
            'portal_url': get_portal_url(self.context),
            'document_base_url': self.context.absolute_url()
        }

        folder = self.context
        if not IFolderish.providedBy(self.context):
            folder = aq_parent(self.context)
        if IPloneSiteRoot.providedBy(folder):
            initial = None
        else:
            initial = IUUID(folder, None)
        current_path = folder.absolute_url()[len(config['portal_url']):]

        # Check if theme has a custom content css
        portal = getSite()
        # Volatile attribute to cache the current theme
        if hasattr(portal, '_v_currentTheme'):
            themeObj = portal._v_currentTheme
        else:
            theme = getCurrentTheme()
            themeObj = getTheme(theme)
            portal._v_currentTheme = themeObj
        cache = component.queryUtility(ram.IRAMCache)
        content_css = None
        if isThemeEnabled(self.request):
            themeObj = cache.query(
                'plone.currentTheme',
                key=dict(prefix='theme'),
                default=None)
            if themeObj is None:
                theme = getCurrentTheme()
                themeObj = getTheme(theme)
                cache.set(
                    themeObj,
                    'plone.currentTheme',
                    key=dict(prefix='theme'))
            if (themeObj and hasattr(themeObj, 'tinymce_content_css') and
                    themeObj.tinymce_content_css):
                content_css = config['portal_url'] + themeObj.tinymce_content_css

        if content_css is None:
            content_css = settings.content_css

        configuration = {
            'relatedItems': format_pattern_settings(
                settings.relatedItems,
                config),
            'upload': {
                'initialFolder': initial,
                'currentPath': current_path,
                'baseUrl': folder.absolute_url(),
                'relativePath': format_pattern_settings(
                    settings.rel_upload_path,
                    config),
                'uploadMultiple': False,
                'maxFiles': 1,
                'showTitle': False
            },
            'base_url': config['document_base_url'],
            'tiny': {
                'content_css': content_css,
            },
            # This is for loading the languages on tinymce
            'loadingBaseUrl': '++plone++static/components/tinymce-builded/js/tinymce',
            'prependToUrl': 'resolveuid/',
            'linkAttribute': format_pattern_settings(
                settings.linkAttribute,
                config),
            'prependToScalePart': format_pattern_settings(
                settings.prependToScalePart,
                config),
            # XXX need to get this from somewhere...
            'folderTypes': ','.join(['Folder']),
            'imageTypes': ','.join(['Image']),
            # 'anchorSelector': utility.anchor_selector,
            # 'linkableTypes': utility.linkable.replace('\n', ',')
        }

        return {'data-pat-tinymce': json.dumps(configuration)}