def test_available_rapido_apps(self): """ Test the list of rapido apps per theme.""" themes = getAvailableRapidoApps(exclude_theme=getCurrentTheme()) self.assertNotEquals(len(themes), 0) self.browser.open(self.portal.absolute_url() + '/@@rapido-store-api?action=list') self.assertEquals(json.loads(self.browser.contents), themes)
def test_available_rapido_apps(self): """ Test the list of rapido apps per theme.""" themes = getAvailableRapidoApps(exclude_theme=getCurrentTheme()) self.assertNotEquals(len(themes), 0) self.browser.open( self.portal.absolute_url() + '/@@rapido-store-api?action=list') self.assertEquals(json.loads(self.browser.contents), themes)
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 setup(self): self.request.response.setHeader('X-Theme-Disabled', '1') processInputs(self.request) self.resourceDirectory = self.context self.theme = getThemeFromResourceDirectory(self.context) self.name = self.resourceDirectory.__name__ self.title = self.theme.title self.portalUrl = getToolByName(self.context, 'portal_url')() self.themeBasePath = "++{0:s}++{1:s}".format( THEME_RESOURCE_NAME, self.name ) self.themeBasePathEncoded = urllib.quote_plus(self.themeBasePath) self.themeBaseUrl = '/'.join([self.portalUrl, self.themeBasePath]) self.editable = IWritableResourceDirectory.providedBy( self.resourceDirectory ) if self.editable: self.resourceUrl = self.resourceDirectory.context.absolute_url() else: self.resourceUrl = None settings = getUtility(IRegistry).forInterface(IThemeSettings, False) self.active = (settings.enabled and self.name == getCurrentTheme()) self.rulesFileName = RULE_FILENAME
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
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)
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
def get_tile_directory(self): theme = getCurrentTheme() if theme: directory = queryResourceDirectory(THEME_RESOURCE_NAME, theme) return directory['tiles'] else: raise NotFound
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
def import_rapido_app(self): app_id = self.request.get("app_id") source_id = self.request.get("source_id") destination_id = self.request.get( "destination_id") or getCurrentTheme() make_link = self.request.get("make_link") == '1' if not source_id: return json.dumps({"error": "No theme id was given", "code": 2}) if not app_id: return json.dumps({"error": "No app id was given", "code": 3}) try: cloneLocalRapidoApp(src_theme=source_id, dest_theme=destination_id, app_id=app_id, make_link=make_link) except RapidoAppNotFound as e: return json.dumps({"error": e.message, "code": 4}) except ThemeNotFound as e: return json.dumps({"error": e.message, "code": 5}) except RapidoAppAlreadyExists as e: return json.dumps({"error": e.message, "code": 6}) return json.dumps({ "message": "{} has been imported in {} theme".format(app_id, destination_id), "error": False })
def get_tile_manager(request=None): if request is None: request = getRequest() cache_key = '{}.manager'.format(CACHE_KEY) if cache_key not in request.environ: if api.env.debug_mode(): request.environ[cache_key] = TileManager() else: # check for value in cache theme = getCurrentTheme() item_cache_key = '{}.manager.{}'.format(CACHE_KEY, theme) if item_cache_key not in _cache: _cache[item_cache_key] = { 'when': time.time(), 'value': TileManager() } else: registry = queryUtility(IRegistry) theme_cache_time = getattr(registry, '_theme_cache_mtime', 0) if theme_cache_time > _cache[item_cache_key]['when']: _cache[item_cache_key] = { 'when': time.time(), 'value': TileManager() } request.environ[cache_key] = _cache[item_cache_key]['value'] return request.environ[cache_key]
def do_action(self, action): if action == "list": apps = getAvailableRapidoApps(exclude_theme=getCurrentTheme()) return json.dumps(apps) elif action == "import": return self.import_rapido_app() return json.dumps({"error": "No request param was given", "code": 1})
def __getattr__(self, name): blacklist = ['im_func', 'func_code', 'index_html'] if name.startswith('_') or name in blacklist: raise AttributeError(name) # Check if there is views/<self.__name__>.<name>.py in the theme, if not raise # noqa currentTheme = getCurrentTheme() if currentTheme is None: raise AttributeError(name) themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme) # noqa if themeDirectory is None: raise AttributeError(name) script = None scriptPath = "%s/%s.py" % (FRAGMENTS_DIRECTORY, self.__name__) if themeDirectory.isFile(scriptPath): script = themeDirectory.readFile(scriptPath) if six.PY3 and isinstance(script, six.binary_type): script = script.decode('utf8') if 'def {0:}(self'.format(name) in script: script += '\n\nreturn {0:s}(self)'.format(name) else: script = None scriptPath = "%s/%s.%s.py" % (FRAGMENTS_DIRECTORY, self.__name__, name) if script is None and themeDirectory.isFile(scriptPath): script = themeDirectory.readFile(scriptPath) if six.PY3 and isinstance(script, six.binary_type): script = script.decode('utf8') if script is None: raise AttributeError(name) # Set the default PythonScript bindings as globals script_globals = { 'script': self, 'context': self.context, 'container': Acquisition.aq_parent(self.context), 'traverse_subpath': '' } # Build re-usable restricted function components like in PythonScript try: code, g, defaults = prepare_restricted_function( 'self,*args,**kwargs', script or 'pass', name, scriptPath, list(script_globals.keys())) except SyntaxError: raise AttributeError(name) # Update globals g = g.copy() g.update(script_globals) g['__file__'] = scriptPath func = types.FunctionType(code, g, None, defaults) # Return the func as instancemethod return types.MethodType(func, self)
def setup(self): self.request.response.setHeader('X-Theme-Disabled', '1') processInputs(self.request) self.resourceDirectory = self.context self.theme = getThemeFromResourceDirectory(self.context) self.name = self.resourceDirectory.__name__ self.title = self.theme.title self.portalUrl = getToolByName(self.context, 'portal_url')() self.themeBasePath = "++%s++%s" % (THEME_RESOURCE_NAME, self.name,) self.themeBasePathEncoded = urllib.quote_plus(self.themeBasePath) self.themeBaseUrl = "%s/%s" % (self.portalUrl, self.themeBasePath,) self.editable = IWritableResourceDirectory.providedBy(self.resourceDirectory) settings = getUtility(IRegistry).forInterface(IThemeSettings, False) self.active = (settings.enabled and self.name == getCurrentTheme()) self.rulesFileName = RULE_FILENAME self.jsVariables = "var CURRENT_SELECTION='%s'; var THEME_BASE_URL='%s'; var THEME_BASE_PATH_ENCODED='%s'; var EDITABLE=%s; var RULE_FILENAME='%s';" % ( self.request.get('file-selector') or '', self.themeBaseUrl, self.themeBasePathEncoded, str(self.editable).lower(), self.rulesFileName )
def get_resource_directory(self): theme = getCurrentTheme() directory = queryResourceDirectory(THEME_RESOURCE_NAME, theme) try: return directory['rapido'][self.id] except NotFound: raise exceptions.NotFound(self.id)
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)
def __getattr__(self, name): blacklist = ['im_func', 'func_code', 'index_html'] if name.startswith('_') or name in blacklist: raise AttributeError(name) # Check if there is views/<self.__name__>.<name>.py in the theme, if not raise # noqa currentTheme = getCurrentTheme() if currentTheme is None: raise AttributeError(name) themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme) # noqa if themeDirectory is None: raise AttributeError(name) script = None scriptPath = "%s/%s.py" % (FRAGMENTS_DIRECTORY, self.__name__) if themeDirectory.isFile(scriptPath): script = themeDirectory.readFile(scriptPath) if 'def {0:}(self'.format(name) in script: script += '\n\nreturn {0:s}(self)'.format(name) else: script = None scriptPath = "%s/%s.%s.py" % (FRAGMENTS_DIRECTORY, self.__name__, name) if script is None and themeDirectory.isFile(scriptPath): script = themeDirectory.readFile(scriptPath) if script is None: raise AttributeError(name) # Set the default PythonScript bindings as globals script_globals = { 'script': self, 'context': self.context, 'container': Acquisition.aq_parent(self.context), 'traverse_subpath': '' } # Build re-usable restricted function components like in PythonScript try: code, g, defaults = prepare_restricted_function( 'self,*args,**kwargs', script or 'pass', name, scriptPath, script_globals.keys() ) except SyntaxError: raise AttributeError(name) # Update globals g = g.copy() g.update(script_globals) g['__file__'] = scriptPath func = new.function(code, g, None, defaults) # Return the func as instancemethod return types.MethodType(func, self)
def do_action(self, action): if action == "list": apps = getAvailableRapidoApps(exclude_theme=getCurrentTheme()) return json.dumps(apps) elif action == "import": return self.import_rapido_app() return json.dumps({ "error": "No request param was given", "code": 1 })
def __init__(self): self.theme = getCurrentTheme() self.site = getSite() if self.theme: directory = queryResourceDirectory(THEME_RESOURCE_NAME, self.theme) try: self.themeDirectory = directory['jbot'] except: self.themeDirectory = None else: self.themeDirectory = None
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 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
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 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
def __init__(self): self._directory = None persistent = getUtility( IResourceDirectory, name="persistent")[RESOURCE_DIRECTORY_NAME] self.directory = persistent['custom'] self.site = getSite() self.theme = getCurrentTheme() if self.theme: directory = queryResourceDirectory( THEME_RESOURCE_NAME, self.theme) try: self.themeDirectory = directory['jbot'] except: self.themeDirectory = None else: self.themeDirectory = None
def activateTheme(): theme = getTheme('custom') if theme is None: createThemeFromTemplate('custom', '') theme = getTheme('custom') directory = queryResourceDirectory(THEME_RESOURCE_NAME, 'custom') try: directory['jbot'] except: directory.makeDirectory('jbot') fi = open(os.path.join(TEST_FILES_DIR, 'footer2.pt')) directory.writeFile('jbot/' + CUSTOMIZED_RESOURCE, fi) fi.close() if getCurrentTheme() != 'custom': applyTheme(theme)
def import_rapido_app(self): app_id = self.request.get("app_id") source_id = self.request.get("source_id") destination_id = self.request.get("destination_id") or getCurrentTheme() make_link = self.request.get("make_link") == '1' if not source_id: return json.dumps({ "error": "No theme id was given", "code": 2 }) if not app_id: return json.dumps({ "error": "No app id was given", "code": 3 }) try: cloneLocalRapidoApp( src_theme=source_id, dest_theme=destination_id, app_id=app_id, make_link=make_link ) except RapidoAppNotFound as e: return json.dumps({ "error": e.message, "code": 4 }) except ThemeNotFound as e: return json.dumps({ "error": e.message, "code": 5 }) except RapidoAppAlreadyExists as e: return json.dumps({ "error": e.message, "code": 6 }) return json.dumps({ "message": "{} has been imported in {} theme".format(app_id, destination_id), "error": False })
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
def setup(self): self.request.response.setHeader('X-Theme-Disabled', '1') processInputs(self.request) self.resourceDirectory = self.context self.theme = getThemeFromResourceDirectory(self.context) self.name = self.resourceDirectory.__name__ self.title = self.theme.title self.portalUrl = getToolByName(self.context, 'portal_url')() self.themeBasePath = "++{0:s}++{1:s}".format(THEME_RESOURCE_NAME, self.name) self.themeBasePathEncoded = urllib.quote_plus(self.themeBasePath) self.themeBaseUrl = '/'.join([self.portalUrl, self.themeBasePath]) self.editable = IWritableResourceDirectory.providedBy( self.resourceDirectory) settings = getUtility(IRegistry).forInterface(IThemeSettings, False) self.active = (settings.enabled and self.name == getCurrentTheme()) self.rulesFileName = RULE_FILENAME
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)
def render_object_html(obj, request): """ Returns rendered html for given content object """ published = request.get('PUBLISHED') if isinstance(published, (BrowserView, FSPageTemplate, PythonScript)): if getCurrentTheme(): transform = ThemeTransform(published, request) try: themed = transform.transformUnicode(published(), 'utf-8') tile_transform = IncludeTiles(published, request) tiled = tile_transform.transformIterable(themed, 'utf-8') if tiled: return tiled.serialize() except Exception, error: log.error("Problem with transforming object %s: %s" % (published, error)) return published() else: try: return published() or '' except NotFound: log.error("Resource '%s' not found" % repr(obj)) return ''
def FragmentTileCacheRuleFactory(obj): from z3c.caching.registry import ICacheRule from z3c.caching.registry import CacheRule noLongerProvides(obj, IFragmentTileCacheRuleLookup) try: default = ICacheRule(obj, None) except TypeError: try: default = ICacheRule(obj.context, None) except (TypeError, AttributeError): default = None try: fragment = obj.context.data['fragment'] except (AttributeError, KeyError): fragment = getFragmentName(getRequest()) if not fragment: return default currentTheme = getCurrentTheme() if not currentTheme: return default themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme) if not themeDirectory: return default rulesets = getFragmentsSettings(themeDirectory, 'themefragments:caching') if not rulesets: return default ruleset = rulesets.get(fragment) if not ruleset: return default return CacheRule(ruleset)
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)
def get_theme_directory(name=None): return queryResourceDirectory( THEME_RESOURCE_NAME, name or getCurrentTheme())
def test_diazo_theme_available(self): from plone.app.theming.utils import getCurrentTheme self.assertTrue(getCurrentTheme() == u'plonetheme.drupal')
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
def getCurrentTheme(self): return getCurrentTheme()
def test_current_theme(self): from plone.app.theming.utils import getCurrentTheme theme = getCurrentTheme() self.assertEqual(theme, u'Default')
def theme(self): _theme = getTheme(getCurrentTheme()) return api.portal.get().absolute_url() + '/' + _theme.production_css
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)}
def test_theme_instaled(self): from plone.app.theming.utils import getCurrentTheme self.assertEqual('ploneintranet.theme', getCurrentTheme())
def test_theme_reset(self): from plone.app.theming.utils import getCurrentTheme self.assertEqual('barceloneta', getCurrentTheme())
def test_diazo_theme_available(self): from plone.app.theming.utils import getCurrentTheme self.assertTrue(getCurrentTheme() == u'plonetheme.depannenergiesnouvelles')
def get_theme_directory(name=None): return queryResourceDirectory(THEME_RESOURCE_NAME, name or getCurrentTheme())