def handleSave(self, action): data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return name = data['name'] title = data['title'] description = data['description'] content = data['content'] filename = data['filename'] title = title.encode('utf-8') description = description.encode('utf-8') directory = queryResourceDirectory(SITE_LAYOUT_RESOURCE_NAME, name) directory.writeFile(MANIFEST_FILENAME, """\ [%s] title = %s description = %s file = %s """ % (SITE_LAYOUT_RESOURCE_NAME, title or '', description or '', filename)) directory.writeFile(filename, content) IStatusMessage(self.request).add(_(u"Changes saved"), type="info") self.request.response.redirect(self.context.absolute_url() + "/@@deco-controlpanel")
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 getSelectedTemplate(self): """ Returns the id of the sticker template selected. If no specific template found in the request (parameter template), returns the default template set in Bika Setup > Stickers. If the template doesn't exist, uses the default bika.lims' Code_128_1x48mm.pt template (was sticker_small.pt). If no template selected but size param, get the sticker template set as default in Bika Setup for the size set. """ bs_template = self.context.bika_setup.getAutoStickerTemplate() size = self.request.get('size', '') if size == 'small': bs_template = self.context.bika_setup.getSmallStickerTemplate() elif size == 'large': bs_template = self.context.bika_setup.getLargeStickerTemplate() rq_template = self.request.get('template', bs_template) # Check if the template exists. If not, fallback to default's prefix = '' if rq_template.find(':') >= 0: prefix, rq_template = rq_template.split(':') templates_dir = queryResourceDirectory('stickers', prefix).directory else: this_dir = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(this_dir, 'templates/stickers/') if not os.path.isfile(os.path.join(templates_dir, rq_template)): rq_template = 'Code_128_1x48mm.pt' return '%s:%s' % (prefix, rq_template) if prefix else rq_template
def onDiscovery(self, theme, settings, dependenciesSettings): res = queryResourceDirectory(THEME_RESOURCE_NAME, theme) if res is None: return directoryName = 'overrides' if 'directory' in settings: directoryName = settings['directory'] if res.isDirectory(directoryName): layer = getattr(schemata, theme, None) if 'layer' in settings: layerName = settings['layer'] try: layer = resolve(layerName) except (ImportError, AttributeError,): logger.warn("Could not import %s" % layerName) return path = os.path.join(res.directory, directoryName) manager = z3c.jbot.metaconfigure.handler(path, layer) self.registered[theme] = manager
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 getSelectedTemplate(self): """ Returns the id of the sticker template selected. If no specific template found in the request (parameter template), returns the default template set in Bika Setup > Stickers. If the template doesn't exist, uses the default bika.lims' Code_128_1x48mm.pt template (was sticker_small.pt). If no template selected but size param, get the sticker template set as default in Bika Setup for the size set. """ bs_template = self.context.bika_setup.getAutoStickerTemplate() size = self.request.get('size', '') if size == 'small': bs_template = self.context.bika_setup.getSmallStickerTemplate() elif size == 'large': bs_template = self.context.bika_setup.getLargeStickerTemplate() rq_template = self.request.get('template', bs_template) # Check if the template exists. If not, fallback to default's prefix = '' if rq_template.find(':') >= 0: prefix, rq_template = rq_template.split(':') templates_dir = queryResourceDirectory('stickers', prefix).directory else: this_dir = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(this_dir, 'templates/stickers/') if not os.path.isfile(os.path.join(templates_dir, rq_template)): rq_template = 'Code_128_1x48mm.pt' return '%s:%s' % (prefix, rq_template) if prefix else rq_template
def getUserContentLayoutsForType(pt): result = [] layout_resources = queryResourceDirectory(CONTENT_LAYOUT_RESOURCE_NAME, 'custom') portal_membership = getToolByName(getSite(), 'portal_membership') user_id = portal_membership.getAuthenticatedMember().getId() try: users_directory = layout_resources['user-layouts'] user_directory = users_directory[user_id] except (NotFound, TypeError): return [] for key, value in getLayoutsFromDirectory( user_directory, CONTENT_LAYOUT_MANIFEST_FORMAT).items(): value['path'] = 'custom/user-layouts/' + key _for = [v for v in (value.get('for') or '').split(',') if v] if _for and pt not in _for: continue preview = value.get('preview', value.get('screenshot')) if preview and not preview.startswith('++'): value[ 'preview'] = '++contentlayout++custom/user-layouts/{user_id}/{path}'.format( user_id=user_id, path='/'.join([os.path.dirname(key), preview])) result.append(value) return result
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 getFormTemplate(self): """Returns the current samplinground rendered with the template specified in the request (param 'template'). Moves the iterator to the next samplinground available. """ templates_dir = self._TEMPLATES_DIR embedt = self.request.get('template', self._DEFAULT_TEMPLATE) if embedt.find(':') >= 0: prefix, embedt = embedt.split(':') templates_dir = queryResourceDirectory(self._TEMPLATES_ADDON_DIR, prefix).directory embed = ViewPageTemplateFile(os.path.join(templates_dir, embedt)) reptemplate = "" try: reptemplate = embed(self) except: tbex = traceback.format_exc() wsid = self._samplingrounds[self._current_sr_index].id reptemplate = "<div class='error-print'>%s - %s '%s':<pre>%s</pre></div>" % ( wsid, _("Unable to load the template"), embedt, tbex) if self._current_sr_index < len(self._samplingrounds): self._current_sr_index += 1 return reptemplate # Using default for now return ViewPageTemplateFile("templates/print/default_form.pt")(self)
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 getUserContentLayoutsForType(pt): result = [] layout_resources = queryResourceDirectory( CONTENT_LAYOUT_RESOURCE_NAME, 'custom' ) portal_membership = getToolByName(getSite(), 'portal_membership') user_id = portal_membership.getAuthenticatedMember().getId() try: users_directory = layout_resources['user-layouts'] user_directory = users_directory[user_id] except (NotFound, TypeError): return [] for key, value in getLayoutsFromDirectory( user_directory, CONTENT_LAYOUT_MANIFEST_FORMAT).items(): value['path'] = 'custom/user-layouts/' + key _for = [v for v in (value.get('for') or '').split(',') if v] if _for and pt not in _for: continue preview = value.get('preview', value.get('screenshot')) if preview and not preview.startswith('++'): value['preview'] = ( '++contentlayout++custom/user-layouts/{user_id}/{path}'.format( user_id=user_id, path='/'.join([os.path.dirname(key), preview]) ) ) result.append(value) return result
def getSelectedTemplateCSS(self): """ Looks for the CSS file from the selected template and return its contents. If the selected template is default.pt, looks for a file named default.css in the stickers path and return its contents. If no CSS file found, retrns an empty string """ prefix, template = self.getSelectedTemplate() # Look for the CSS content = '' ''' if template.find(':') >= 0: # A template from another add-on prefix, template = template.split(':') resource = queryResourceDirectory('stickers', prefix) css = '{0}.css'.format(template[:-3]) if css in resource.listDirectory(): content = resource.readFile(css) ''' if prefix: resource = queryResourceDirectory('stickers', prefix) css = '{0}.css'.format(template[:-3]) if css in resource.listDirectory(): content = resource.readFile(css) else: this_dir = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(this_dir, 'templates/stickers/') path = '%s/%s.css' % (templates_dir, template[:-3]) if os.path.isfile(path): with open(path, 'r') as content_file: content = content_file.read() return content
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 deletelayout(self): layout_resources = queryResourceDirectory( CONTENT_LAYOUT_RESOURCE_NAME, 'custom') # find directory layout_path = self.request.form.get('layout') filename = layout_path.split('/')[-1] directory = layout_resources for part in layout_path.replace('custom/', '').split('/')[:-1]: directory = directory[part] del directory[filename] # now to modify manifest to not include if MANIFEST_FILENAME in directory.listDirectory(): manifest = loadManifest(directory.readFile(MANIFEST_FILENAME)) removeLayout(manifest, filename) directory.writeFile(MANIFEST_FILENAME, dumpManifest(manifest)) # now reassign if provided replacement = self.request.form.get('replacement') if replacement: replacement = self._get_layout_path(replacement) catalog = api.portal.get_tool('portal_catalog') for brain in catalog(layout=self._get_layout_path(layout_path)): obj = brain.getObject() layout_data = ILayoutAware(obj, None) if layout_data: layout_data.contentLayout = replacement obj.reindexObject(idxs=['layout']) return json.dumps({ 'success': True, 'user_layouts': getUserContentLayoutsForType(self.context.portal_type), 'available_layouts': getContentLayoutsForType(self.context.portal_type) })
def getSelectedTemplate(self): """ Returns the id of the sticker template selected. If no specific template found in the request (parameter template), returns the default template set in Bika Setup > Stickers. If the template doesn't exist, uses the default bika.lims' Code_128_1x48mm.pt template (was sticker_small.pt). If no template selected but size param, get the sticker template set as default in Bika Setup for the size set. """ bs_template = self.context.bika_setup.getAutoStickerTemplate() size = self.request.get("size", "") if size == "small": bs_template = self.context.bika_setup.getSmallStickerTemplate() elif size == "large": bs_template = self.context.bika_setup.getLargeStickerTemplate() rq_template = self.request.get("template", bs_template) # Check if the template exists. If not, fallback to default's if rq_template.find(":") >= 0: prefix, rq_template = rq_template.split(":") templates_dir = queryResourceDirectory("stickers", prefix).directory else: this_dir = os.path.dirname(os.path.abspath(__file__)) templates_dir = os.path.join(this_dir, "templates/stickers/") if not os.path.isfile(os.path.join(templates_dir, rq_template)): rq_template = "Code_128_1x48mm.pt" return rq_template
def onDiscovery(self, theme, settings, dependenciesSettings): res = queryResourceDirectory(THEME_RESOURCE_NAME, theme) if res is None: return directoryName = 'overrides' if 'directory' in settings: directoryName = settings['directory'] if res.isDirectory(directoryName): layer = getattr(schemata, theme, None) if 'layer' in settings: layerName = settings['layer'] try: layer = resolve(layerName) except ( ImportError, AttributeError, ): logger.warn("Could not import %s" % layerName) return path = os.path.join(res.directory, directoryName) manager = z3c.jbot.metaconfigure.handler(path, layer) self.registered[theme] = manager
def getContent(self): name = self.request.get('name', self.request.get('form.widgets.name')) title = u"" description = u"" filename = SITE_LAYOUT_FILE_NAME directory = queryResourceDirectory(SITE_LAYOUT_RESOURCE_NAME, name) if directory.isFile(MANIFEST_FILENAME): manifest = getManifest(directory.openFile(MANIFEST_FILENAME), SITE_LAYOUT_MANIFEST_FORMAT) title = manifest.get('title', title) description = manifest.get('description', description) filename = manifest.get('file', filename) if isinstance(title, str): title = title.decode('utf-8') if isinstance(description, str): description = description.decode('utf-8') content = directory.readFile(filename) return { 'name': name, 'filename': filename, 'title': title, 'description': description, 'content': content, }
def save(self): form = self.request.form layout_dir_name = 'custom' layout_resources = queryResourceDirectory(CONTENT_LAYOUT_RESOURCE_NAME, layout_dir_name) if form.get('global', '').lower() not in ('y', 't', 'true', '1'): # get/create layout directory for user user_id = api.user.get_current().getId() try: users_directory = layout_resources['user-layouts'] except NotFound: layout_resources.makeDirectory('user-layouts') users_directory = layout_resources['user-layouts'] try: user_directory = users_directory[user_id] except NotFound: users_directory.makeDirectory(user_id) user_directory = users_directory[user_id] layout_dir_name = 'custom/user-layouts/' + user_id layout_resources = user_directory normalizer = getUtility(IIDNormalizer) layout_filename = normalizer.normalize(form['name']) + '.html' count = 0 while layout_filename in layout_resources.listDirectory(): count += 1 layout_filename = normalizer.normalize(form['name'] + '-' + str(count)) + '.html' layout_resources.writeFile(layout_filename, form['layout']) # need to read manifest and add to it dynamically here for the new layout if MANIFEST_FILENAME in layout_resources.listDirectory(): manifest = loadManifest( layout_resources.readFile(MANIFEST_FILENAME)) else: manifest = loadManifest('') sections = manifest.sections() manifest.add_section('new') # section name is a bit indeterminate when the multidict implementation section_name = list(set(manifest.sections()) - set(sections))[0] manifest.set(section_name, 'title', form['name']) manifest.set(section_name, 'file', layout_filename) manifest.set(section_name, 'for', self.context.portal_type) layout_resources.writeFile(MANIFEST_FILENAME, dumpManifest(manifest)) return json.dumps({ 'success': True, 'layout': '++contentlayout++%s/%s' % (layout_dir_name, layout_filename), 'user_layouts': getUserContentLayoutsForType(self.context.portal_type), 'available_layouts': getContentLayoutsForType(self.context.portal_type) })
def renderItem(self): """ Renders the next available sticker. Uses the template specified in the request ('template' parameter) by default. If no template defined in the request, uses the default template set by default in Bika Setup > Stickers. If the template specified doesn't exist, uses the default bika.lims' Code_128_1x48mm.pt template (was sticker_small.pt). """ curritem = self.nextItem() templates_dir = 'templates/stickers' prefix, embedt = self.getSelectedTemplate() if prefix: templates_dir = queryResourceDirectory('stickers', prefix).directory ''' if embedt.find(':') >= 0: prefix, embedt = embedt.split(':') templates_dir = queryResourceDirectory('stickers', prefix).directory ''' fullpath = os.path.join(templates_dir, embedt) try: embed = ViewPageTemplateFile(fullpath) return embed(self) except: tbex = traceback.format_exc() stickerid = curritem[2].id if curritem[2] else curritem[1].id return "<div class='error'>%s - %s '%s':<pre>%s</pre></div>" % \ (stickerid, _("Unable to load the template"), embedt, tbex)
def get_tile_directory(self): theme = getCurrentTheme() if theme: directory = queryResourceDirectory(THEME_RESOURCE_NAME, theme) return directory['tiles'] else: raise NotFound
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 __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 test_editor_can_delete_user_layout(self): # first, add layout self.request.form.update({ 'action': 'save', 'name': 'my-layout', 'global': 'false', 'layout': '<html><body>foobar</body></html>' }) login(self.portal, TEST_USER_NAME) setRoles(self.portal, TEST_USER_ID, ['Editor']) self.portal.restrictedTraverse('@@manage-layouts-from-editor')() layout_resources = queryResourceDirectory( CONTENT_LAYOUT_RESOURCE_NAME, 'custom') user_directory = layout_resources['user-layouts/' + TEST_USER_ID] self.assertTrue('my-layout.html' in user_directory.listDirectory()) # now try to delete user layout self.request.form.update({ 'action': 'deletelayout', 'layout': 'custom/user-layouts/{}/my-layout.html'.format(TEST_USER_ID) }) self.portal.restrictedTraverse('@@manage-layouts-from-editor')() self.assertTrue('my-layout.html' not in user_directory.listDirectory())
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 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 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 __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 onDisabled(self, theme, settings, dependenciesSettings): # noqa res = queryResourceDirectory(THEME_RESOURCE_NAME, theme) if res is None: return # We need to get settings by ourselves to avoid p.a.theming caching settings = getSettings(res) if not isEnabled(settings): return directoryName = DEFAULT_DISABLED_PROFILE_NAME if 'uninstall' in settings: directoryName = settings['uninstall'] # Import GS (uninstall) profile directory = None if res.isDirectory(directoryName): directory = res[directoryName] if directory: tarball = createTarball(directory) portal_setup = api.portal.get_tool('portal_setup') portal_setup.runAllImportStepsFromProfile( None, purge_old=False, archive=tarball) # Unregister ALL themesitesetup based permissions sm = getSiteManager() permissions = getPermissions(settings) for key, util in list(sm.getUtilitiesFor(IPermission)): if isinstance(util, Permission) or isinstance(util, LocalPermission): # noqa name = str('collective.themesitesetup.permission.' + key) if key not in permissions and name not in sm.objectIds(): continue # Not a themesitesetup created permission if name in list(sm.objectIds()): sm._delObject(name, suppress_events=True) # Note: The following lines may look weird, but exist because # we used to use transient Persistent class and these were the # lines, which properly unregistered those. util = sm._utility_registrations.get((IPermission, key))[0] sm.unregisterUtility( util, provided=IPermission, name=key) sm.utilities.unsubscribe((), IPermission, util) # Unregister ALL themesitesetup based locales for domain, util in list(sm.getUtilitiesFor(ITranslationDomain)): util = sm.queryUtility(ITranslationDomain, name=domain) if isinstance(util, TranslationDomain): for name in list(util): if not name.startswith('collective.themesitesetup.catalog.'): # noqa continue # not a themesitesetup created domain try: del util[name] except ValueError: pass name = str('collective.themesitesetup.domain.' + domain) if name in list(sm.objectIds()): sm._delObject(name, suppress_events=True) sm.unregisterUtility( util, provided=ITranslationDomain, name=domain)
def update(self): form = self.request.form self.settings = getUtility(IRegistry).forInterface( IThemeSettings, False) gallerysettings = getUtility(IRegistry).forInterface( IThemeGallerySettingsSchema, False) url = gallerysettings.tgserver_url if not url.endswith('/'): url +='/' self.base_url = '%s__rest__/cms/content:themes' % url self.api = '%s__rest__/cms/applications' % url if 'form.button.install' in form: theme = form.get('theme_uuid', None) if theme is not None: tfile = self.loadTheme(theme) try: themeZip = zipfile.ZipFile(tfile) except (zipfile.BadZipfile, zipfile.LargeZipFile,): logger.exception("Could not read zip file") self.error = u"The uploaded file is not a valid Zip archive" return if themeZip: try: themeData = extractThemeInfo(themeZip) except (ValueError, KeyError,), e: logger.warn(str(e)) self.error = u"The uploaded file does not contain a valid theme archive." else: themeContainer=getOrCreatePersistentResourceDirectory() themeExists = themeData.__name__ in themeContainer if themeExists: del themeContainer[themeData.__name__] themeContainer.importZip(themeZip) themeDirectory = queryResourceDirectory( THEME_RESOURCE_NAME, themeData.__name__) if themeDirectory is not None: plugins = getPlugins() pluginSettings = getPluginSettings( themeDirectory, plugins) if pluginSettings is not None: for name, plugin in plugins: plugin.onCreated( themeData.__name__, pluginSettings[name], pluginSettings) applyTheme(themeData) self.settings.enabled = True IStatusMessage(self.request).add( "Theme has been installed.")
def __call__(self): self.errors = {} if self.request.method == 'POST': CheckAuthenticator(self.request) catalog = getToolByName(self.context, 'portal_catalog') form = self.request.form if 'form.button.SaveGeneral' in form: name = form.get('defaultSiteLayout') directory = queryResourceDirectory(SITE_LAYOUT_RESOURCE_NAME, name) if directory is None: IStatusMessage(self.request).add(_(u"Cannot find resource directory"), type="error") else: filename = SITE_LAYOUT_FILE_NAME if directory.isFile(MANIFEST_FILENAME): manifest = getManifest(directory.openFile(MANIFEST_FILENAME), SITE_LAYOUT_MANIFEST_FORMAT) filename = manifest.get('file', filename) registry = getUtility(IRegistry) registry['plone.defaultSiteLayout'] = "./++%s++%s/%s" % \ (SITE_LAYOUT_RESOURCE_NAME, name, filename) IStatusMessage(self.request).add(_(u"Default site layout updated"), type="info") elif 'form.button.DeletePageType' in form: portal_type = form.get('name') if portal_type == DEFAULT_PAGE_TYPE_NAME: IStatusMessage(self.request).add(_(u"Cannot delete the default page type"), type="error") elif len(catalog({'portal_type': portal_type})) > 0: IStatusMessage(self.request).add(_(u"Cannot delete a type that is in use"), type="error") else: portal_types = getToolByName(self, 'portal_types') del portal_types[portal_type] IStatusMessage(self.request).add(_(u"Type deleted"), type="info") elif 'form.button.DeleteSiteLayout' in form: name = form.get('name') resources = getUtility(IResourceDirectory, name='persistent') sitelayouts = resources[SITE_LAYOUT_RESOURCE_NAME] del sitelayouts[name] IStatusMessage(self.request).add(_(u"Site layout deleted"), type="info") elif 'form.button.DeletePageLayout' in form: name = form.get('name') resources = getUtility(IResourceDirectory, name='persistent') pagelayouts = resources[PAGE_LAYOUT_RESOURCE_NAME] del pagelayouts[name] IStatusMessage(self.request).add(_(u"Page layout deleted"), type="info") return self.index()
def deletelayout(self): layout_resources = queryResourceDirectory( CONTENT_LAYOUT_RESOURCE_NAME, 'custom') layout_path = self.request.form.get('layout') if len(layout_path.split('/')) <= 2: sm = getSecurityManager() # this is a global layout, need to check permissions if not sm.checkPermission('Plone: Manage Content Layouts', api.portal.get()): raise Unauthorized("User not allowed to delete global layout") else: # check this user is allowed to delete this template user_dir = 'custom/user-layouts/{0:s}'.format( api.user.get_current().getId()) if not layout_path.startswith(user_dir): raise Unauthorized("You are not allowed to delete this layout") # find directory filename = layout_path.split('/')[-1] directory = layout_resources for part in layout_path.replace('custom/', '').split('/')[:-1]: directory = directory[part] del directory[filename] # now to modify manifest to not include if MANIFEST_FILENAME in directory.listDirectory(): manifest = loadManifest(directory.readFile(MANIFEST_FILENAME)) removeLayout(manifest, filename) directory.writeFile(MANIFEST_FILENAME, dumpManifest(manifest)) # now reassign if provided replacement = self.request.form.get('replacement') if replacement: replacement = self._get_layout_path(replacement) catalog = api.portal.get_tool('portal_catalog') for brain in catalog(layout=self._get_layout_path(layout_path)): obj = brain.getObject() layout_data = ILayoutAware(obj, None) if layout_data: layout_data.contentLayout = replacement obj.reindexObject(idxs=['layout']) return json.dumps( { 'success': True, 'user_layouts': getUserContentLayoutsForType( self.context.portal_type ), 'available_layouts': getContentLayoutsForType( self.context.portal_type, self.context ) } )
def deletelayout(self): layout_resources = queryResourceDirectory( CONTENT_LAYOUT_RESOURCE_NAME, 'custom') layout_path = self.request.form.get('layout') if len(layout_path.split('/')) <= 2: sm = getSecurityManager() # this is a global layout, need to check permissions if not sm.checkPermission('Plone: Manage Content Layouts', api.portal.get()): raise Unauthorized("User not allowed to delete global layout") else: # check this user is allowed to delete this template user_dir = 'custom/user-layouts/{}'.format( api.user.get_current().getId()) if not layout_path.startswith(user_dir): raise Unauthorized("You are not allowed to delete this layout") # find directory filename = layout_path.split('/')[-1] directory = layout_resources for part in layout_path.replace('custom/', '').split('/')[:-1]: directory = directory[part] del directory[filename] # now to modify manifest to not include if MANIFEST_FILENAME in directory.listDirectory(): manifest = loadManifest(directory.readFile(MANIFEST_FILENAME)) removeLayout(manifest, filename) directory.writeFile(MANIFEST_FILENAME, dumpManifest(manifest)) # now reassign if provided replacement = self.request.form.get('replacement') if replacement: replacement = self._get_layout_path(replacement) catalog = api.portal.get_tool('portal_catalog') for brain in catalog(layout=self._get_layout_path(layout_path)): obj = brain.getObject() layout_data = ILayoutAware(obj, None) if layout_data: layout_data.contentLayout = replacement obj.reindexObject(idxs=['layout']) return json.dumps( { 'success': True, 'user_layouts': getUserContentLayoutsForType( self.context.portal_type ), 'available_layouts': getContentLayoutsForType( self.context.portal_type ) } )
def save(self): form = self.request.form layout_dir_name = 'custom' layout_resources = queryResourceDirectory( CONTENT_LAYOUT_RESOURCE_NAME, layout_dir_name) if form.get('global', '').lower() not in ('y', 't', 'true', '1'): # get/create layout directory for user user_id = api.user.get_current().getId() try: users_directory = layout_resources['user-layouts'] except NotFound: layout_resources.makeDirectory('user-layouts') users_directory = layout_resources['user-layouts'] try: user_directory = users_directory[user_id] except NotFound: users_directory.makeDirectory(user_id) user_directory = users_directory[user_id] layout_dir_name = 'custom/user-layouts/' + user_id layout_resources = user_directory normalizer = getUtility(IIDNormalizer) layout_filename = normalizer.normalize(form['name']) + '.html' count = 0 while layout_filename in layout_resources.listDirectory(): count += 1 layout_filename = normalizer.normalize(form['name'] + '-' + str(count)) + '.html' layout_resources.writeFile(layout_filename, form['layout']) # need to read manifest and add to it dynamically here for the new layout if MANIFEST_FILENAME in layout_resources.listDirectory(): manifest = loadManifest(layout_resources.readFile(MANIFEST_FILENAME)) else: manifest = loadManifest('') sections = manifest.sections() manifest.add_section('new') # section name is a bit indeterminate when the multidict implementation section_name = list(set(manifest.sections()) - set(sections))[0] manifest.set(section_name, 'title', form['name']) manifest.set(section_name, 'file', layout_filename) manifest.set(section_name, 'for', self.context.portal_type) layout_resources.writeFile(MANIFEST_FILENAME, dumpManifest(manifest)) return json.dumps({ 'success': True, 'layout': '++contentlayout++%s/%s' % (layout_dir_name, layout_filename), 'user_layouts': getUserContentLayoutsForType(self.context.portal_type), 'available_layouts': getContentLayoutsForType(self.context.portal_type) })
def __init__(self, theme, template_cache=None, *args, **kwargs): self.file_cache = {} if template_cache is None: template_cache = {} self.template_cache = template_cache self.theme = theme try: self.folder = queryResourceDirectory(THEME_RESOURCE_NAME, theme) except: self.folder = None super(PageTemplateLoader, self).__init__(*args, **kwargs)
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 traverse(self, name, remaining): _type = self.name # Note: also fixes possible unicode problems name = urllib.parse.quote(name) res = queryResourceDirectory(_type, name) if res is not None: return res raise NotFound
def traverse(self, name, remaining): _type = self.name # Note: also fixes possible unicode problems name = urllib.quote(name) res = queryResourceDirectory(_type, name) if res is not None: return res raise NotFound
def applyTheme(theme): """Apply an ITheme """ settings = getUtility(IRegistry).forInterface(IThemeSettings, False) plugins = None themeDirectory = None pluginSettings = None currentTheme = getCurrentTheme() if currentTheme is not None: themeDirectory = queryResourceDirectory( THEME_RESOURCE_NAME, currentTheme) if themeDirectory is not None: plugins = getPlugins() pluginSettings = getPluginSettings(themeDirectory, plugins) if theme is None: settings.currentTheme = None settings.rules = None settings.absolutePrefix = None settings.parameterExpressions = {} settings.doctype = "" if pluginSettings is not None: for name, plugin in plugins: plugin.onDisabled(currentTheme, pluginSettings[name], pluginSettings) else: if isinstance(theme.rules, str): theme.rules = theme.rules.decode('utf-8') if isinstance(theme.absolutePrefix, str): theme.absolutePrefix = theme.absolutePrefix.decode('utf-8') if isinstance(theme.__name__, str): theme.__name__ = theme.__name__.decode('utf-8') settings.currentTheme = theme.__name__ settings.rules = theme.rules settings.absolutePrefix = theme.absolutePrefix settings.parameterExpressions = theme.parameterExpressions settings.doctype = theme.doctype if pluginSettings is not None: for name, plugin in plugins: plugin.onDisabled(currentTheme, pluginSettings[name], pluginSettings) plugin.onEnabled(theme, pluginSettings[name], pluginSettings) notify(ThemeAppliedEvent(theme))
def test_manager_can_delete_global_layout(self): self.request.form.update({ 'action': 'deletelayout', 'layout': 'custom/basic.html' }) login(self.portal, TEST_USER_NAME) setRoles(self.portal, TEST_USER_ID, ['Manager']) self.portal.restrictedTraverse('@@manage-layouts-from-editor')() layout_resources = queryResourceDirectory( CONTENT_LAYOUT_RESOURCE_NAME, 'custom') self.assertTrue('basic.html' not in layout_resources.listDirectory())
def applyTheme(theme): """Apply an ITheme """ settings = getUtility(IRegistry).forInterface(IThemeSettings, False) plugins = None themeDirectory = None pluginSettings = None currentTheme = getCurrentTheme() if currentTheme is not None: themeDirectory = queryResourceDirectory( THEME_RESOURCE_NAME, currentTheme) if themeDirectory is not None: plugins = getPlugins() pluginSettings = getPluginSettings(themeDirectory, plugins) if theme is None: settings.currentTheme = None settings.rules = None settings.absolutePrefix = None settings.parameterExpressions = {} settings.doctype = "" if pluginSettings is not None: for name, plugin in plugins: plugin.onDisabled(currentTheme, pluginSettings[name], pluginSettings) else: if isinstance(theme.rules, str): theme.rules = theme.rules.decode('utf-8') if isinstance(theme.absolutePrefix, str): theme.absolutePrefix = theme.absolutePrefix.decode('utf-8') if isinstance(theme.__name__, str): theme.__name__ = theme.__name__.decode('utf-8') settings.currentTheme = theme.__name__ settings.rules = theme.rules settings.absolutePrefix = theme.absolutePrefix settings.parameterExpressions = theme.parameterExpressions settings.doctype = theme.doctype if pluginSettings is not None: for name, plugin in plugins: plugin.onDisabled(currentTheme, pluginSettings[name], pluginSettings) plugin.onEnabled(theme, pluginSettings[name], pluginSettings)
def traverse(self, name, remaining): if name == '': name = self.current_theme() # Note: also fixes possible unicode problems name = urllib.quote(name) res = queryResourceDirectory(self.name, name) if res is not None: return res raise NotFound
def traverse(self, name, remaining): if name == '': name = self.current_theme() # Note: also fixes possible unicode problems name = urllib.quote(name) res = queryResourceDirectory(self.name, name) if res is not None: return res raise NotFound
def _renderTemplate(self): """ Returns the html template to be rendered in accordance with the template specified in the request ('template' parameter) """ templates_dir = 'templates/reports' embedt = self.request.form.get('template', self._DEFAULT_TEMPLATE) if embedt.find(':') >= 0: prefix, template = embedt.split(':') templates_dir = queryResourceDirectory('reports', prefix).directory embedt = template embed = ViewPageTemplateFile(os.path.join(templates_dir, embedt)) return embedt, embed(self)
def _renderTemplate(self): """ Returns the html template to be rendered in accordance with the template specified in the request ('template' parameter) """ templates_dir = 'templates/reports' embedt = self.request.form.get('template', self._DEFAULT_TEMPLATE) if embedt.find(':') >= 0: prefix, template = embedt.split(':') templates_dir = queryResourceDirectory('reports', prefix).directory embedt = template embed = ViewPageTemplateFile(os.path.join(templates_dir, embedt)) return embedt, embed(self)
def test_createTemplatePageLayout(self): from plone.app.page.interfaces import PAGE_LAYOUT_MANIFEST_FORMAT from plone.app.page.utils import createTemplatePageLayout from plone.resource.utils import queryResourceDirectory from plone.resource.manifest import getManifest from plone.app.testing import TEST_USER_ID from plone.app.testing import setRoles portal = self.layer['portal'] setRoles(portal, TEST_USER_ID, ('Manager',)) createTemplatePageLayout(u"A title", u"A description", u"<html><body><p>Stuff</p></body></html>") setRoles(portal, TEST_USER_ID, ('Member',)) directory = queryResourceDirectory('pagelayout', 'a-title') self.assertTrue('page.html' in directory) self.assertTrue('manifest.cfg' in directory) self.assertEqual(directory.readFile('page.html'), "<html><body><p>Stuff</p></body></html>") manifest = getManifest(directory.openFile('manifest.cfg'), PAGE_LAYOUT_MANIFEST_FORMAT) self.assertEqual(manifest, {'title': "A title", 'description': "A description", 'file': 'page.html'}) # Create a second one with the same title setRoles(portal, TEST_USER_ID, ('Manager',)) createTemplatePageLayout(u"A title", u"Another description", u"<html><body><p>Other stuff</p></body></html>") setRoles(portal, TEST_USER_ID, ('Member',)) directory = queryResourceDirectory('pagelayout', 'a-title-1') self.assertTrue('page.html' in directory) self.assertTrue('manifest.cfg' in directory) self.assertEqual(directory.readFile('page.html'), "<html><body><p>Other stuff</p></body></html>") manifest = getManifest(directory.openFile('manifest.cfg'), PAGE_LAYOUT_MANIFEST_FORMAT) self.assertEqual(manifest, {'title': "A title", 'description': "Another description", 'file': 'page.html'})
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 _getStickersTemplatesDirectory(self, resource_name): """Returns the paths for the directory containing the css and pt files for the stickers deppending on the filter_by_type. :param resource_name: The name of the resource folder. :type resource_name: string :returns: a string as a path """ templates_dir =\ queryResourceDirectory("stickers", resource_name).directory if self.filter_by_type: templates_dir = templates_dir + "/" + self.filter_by_type return templates_dir
def createThemeFromTemplate(title, description, baseOn='template'): """Create a new theme from the given title and description based on another theme resource directory """ source = queryResourceDirectory(THEME_RESOURCE_NAME, baseOn) if source is None: raise KeyError("Theme %s not found" % baseOn) themeName = getUtility(IURLNormalizer).normalize(title) if isinstance(themeName, unicode): themeName = themeName.encode('utf-8') resources = getOrCreatePersistentResourceDirectory() if themeName in resources: idx = 1 while "%s-%d" % ( themeName, idx, ) in resources: idx += 1 themeName = "%s-%d" % ( themeName, idx, ) resources.makeDirectory(themeName) target = resources[themeName] cloneResourceDirectory(source, target) manifest = SafeConfigParser() if MANIFEST_FILENAME in target: fp = target.openFile(MANIFEST_FILENAME) try: manifest.readfp(fp) finally: fp.close() if not manifest.has_section('theme'): manifest.add_section('theme') manifest.set('theme', 'title', title) manifest.set('theme', 'description', description) manifestContents = StringIO() manifest.write(manifestContents) target.writeFile(MANIFEST_FILENAME, manifestContents) return themeName
def createThemeFromTemplate(title, description, baseOn='template'): """Create a new theme from the given title and description based on another theme resource directory """ source = queryResourceDirectory(THEME_RESOURCE_NAME, baseOn) if source is None: raise KeyError("Theme {0:s} not found".format(baseOn)) themeName = getUtility(IURLNormalizer).normalize(title) if isinstance(themeName, unicode): themeName = themeName.encode('utf-8') resources = getOrCreatePersistentResourceDirectory() resources.makeDirectory(themeName) target = resources[themeName] cloneResourceDirectory(source, target) manifest = SafeConfigParser() if MANIFEST_FILENAME in target: fp = target.openFile(MANIFEST_FILENAME) try: manifest.readfp(fp) finally: fp.close() if not manifest.has_section('theme'): manifest.add_section('theme') manifest.set('theme', 'title', title) manifest.set('theme', 'description', description) if manifest.has_option('theme', 'prefix'): prefix = u"/++%s++%s" % (THEME_RESOURCE_NAME, themeName) manifest.set('theme', 'prefix', prefix) if manifest.has_option('theme', 'rules'): rule = manifest.get('theme', 'rules') rule_file_name = rule.split('/')[-1] # extract real rules file name rules = u"/++%s++%s/%s" % (THEME_RESOURCE_NAME, themeName, rule_file_name) manifest.set('theme', 'rules', rules) manifestContents = StringIO() manifest.write(manifestContents) target.writeFile(MANIFEST_FILENAME, manifestContents) return themeName
def applyTheme(theme): """Apply an ITheme """ toadapt = (getSite(), getRequest()) settings = getMultiAdapter(toadapt, IThemeSettings) plugins = None themeDirectory = None pluginSettings = None currentTheme = getCurrentTheme() if currentTheme is not None: themeDirectory = queryResourceDirectory(THEME_RESOURCE_NAME, currentTheme) if themeDirectory is not None: plugins = getPlugins() pluginSettings = getPluginSettings(themeDirectory, plugins) if theme is None: settings.currentTheme = None settings.rules = None settings.absolutePrefix = None settings.parameterExpressions = {} settings.doctype = "" if pluginSettings is not None: for name, plugin in plugins: plugin.onDisabled(currentTheme, pluginSettings[name], pluginSettings) else: if isinstance(theme.rules, str): theme.rules = theme.rules.decode("utf-8") if isinstance(theme.absolutePrefix, str): theme.absolutePrefix = theme.absolutePrefix.decode("utf-8") if isinstance(theme.__name__, str): theme.__name__ = theme.__name__.decode("utf-8") settings.currentTheme = theme.__name__ settings.rules = theme.rules settings.absolutePrefix = theme.absolutePrefix settings.parameterExpressions = theme.parameterExpressions settings.doctype = theme.doctype if pluginSettings is not None: for name, plugin in plugins: plugin.onDisabled(currentTheme, pluginSettings[name], pluginSettings) plugin.onEnabled(theme, pluginSettings[name], pluginSettings)
def createThemeFromTemplate(title, description, baseOn='template'): """Create a new theme from the given title and description based on another theme resource directory """ source = queryResourceDirectory(THEME_RESOURCE_NAME, baseOn) if source is None: raise KeyError("Theme {0:s} not found".format(baseOn)) themeName = getUtility(IURLNormalizer).normalize(title) if isinstance(themeName, unicode): themeName = themeName.encode('utf-8') resources = getOrCreatePersistentResourceDirectory() resources.makeDirectory(themeName) target = resources[themeName] cloneResourceDirectory(source, target) manifest = SafeConfigParser() if MANIFEST_FILENAME in target: fp = target.openFile(MANIFEST_FILENAME) try: manifest.readfp(fp) finally: fp.close() if not manifest.has_section('theme'): manifest.add_section('theme') manifest.set('theme', 'title', title) manifest.set('theme', 'description', description) if manifest.has_option('theme', 'prefix'): prefix = u"/++%s++%s" % (THEME_RESOURCE_NAME, themeName) manifest.set('theme', 'prefix', prefix) if manifest.has_option('theme', 'rules'): rule = manifest.get('theme', 'rules') rule_file_name = rule.split('/')[-1] # extract real rules file name rules = u"/++%s++%s/%s" % (THEME_RESOURCE_NAME, themeName, rule_file_name) manifest.set('theme', 'rules', rules) manifestContents = StringIO() manifest.write(manifestContents) target.writeFile(MANIFEST_FILENAME, manifestContents) return themeName
def getCSS(self): """ Returns the css style to be used for the current template. If the selected template is 'default.pt', this method will return the content from 'default.css'. If no css file found for the current template, returns empty string """ template = self.request.get('template', self._DEFAULT_TEMPLATE) content = '' prefix, filename = template.split(':') resource = queryResourceDirectory(self._TEMPLATES_ADDON_DIR, prefix) css = '{0}.css'.format(filename[:-3]) if css in resource.listDirectory(): content = resource.readFile(css) return content
def test_manager_can_save_global_layout(self): self.request.form.update({ 'action': 'save', 'name': 'my-layout', 'global': 'true', 'layout': '<html><body>foobar</body></html>' }) login(self.portal, TEST_USER_NAME) setRoles(self.portal, TEST_USER_ID, ['Manager']) self.portal.restrictedTraverse('@@manage-layouts-from-editor')() layout_resources = queryResourceDirectory( CONTENT_LAYOUT_RESOURCE_NAME, 'custom') self.assertEqual( str(layout_resources['my-layout.html']), '<html><body>foobar</body></html>')
def get_directory(self, policy=None): if policy is None: policy = theming_policy() current_theme = policy.getCurrentTheme() if current_theme is None: raise KeyError() theme_directory = queryResourceDirectory( THEME_RESOURCE_NAME, current_theme) if theme_directory is None: raise KeyError() return theme_directory
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 __call__(self): bc = getToolByName(self.context, 'bika_catalog') items = self.request.get('items', '') if items: self.items = [o.getObject() for o in bc(id=items.split(","))] else: self.items = [ self.context, ] # ARs get stickers for their respective samples. new_items = [] for i in self.items: if i.portal_type == 'AnalysisRequest': new_items.append(i.getSample()) else: new_items.append(i) self.items = new_items # Samples get stickers for their partitions. new_items = [] for i in self.items: if i.portal_type == 'Sample': new_items += i.objectValues('SamplePartition') else: new_items.append(i) self.items = new_items if not self.items: logger.warning( "Cannot print stickers: no items specified in request") self.request.response.redirect(self.context.absolute_url()) return if self.items[0].portal_type == 'SamplePartition': template = self.request.get('template', '') prefix, tmpl = template.split(':') templates_dir = queryResourceDirectory('stickers', prefix).directory stickertemplate = ViewPageTemplateFile( os.path.join(templates_dir, tmpl)) return stickertemplate(self) elif self.items[0].portal_type == 'ReferenceSample': return self.referencesample_sticker()
def getOrderTemplate(self): templates_dir = 'templates/sheets' embedt = self.request.form.get('template', self._DEFAULT_TEMPLATE) if embedt.find(':') >= 0: prefix, template = embedt.split(':') templates_dir = queryResourceDirectory('sheets', prefix).directory embedt = template embed = ViewPageTemplateFile(os.path.join(templates_dir, embedt)) reptemplate = "" try: reptemplate = embed(self) except: tbex = traceback.format_exc() arid = self._products[self._current_product_index].id reptemplate = "<div class='error-report'>%s - %s '%s':<pre>%s</pre></div>" % ( arid, _("Unable to load the template"), embedt, tbex) self._nextProduct() return reptemplate