def generatePDF(self, REQUEST=None, RESPONSE=None, *args, **kwargs) : """ generates the PDF with form filled in """ if not self.hasPdfContent() : raise EmptyERP5PdfFormError, 'Pdf content must be downloaded first' values = self.calculateCellValues(REQUEST, *args, **kwargs) context = { 'here' : self.aq_parent, 'context' : self.aq_parent, 'request' : REQUEST } if self.__format_method__: compiled_tales = getEngine().compile(self.__format_method__) format_method = getEngine().getContext(context).evaluate(compiled_tales) # try to support both method name and method object if not callable(format_method) : format_method = self.restrictedTraverse(format_method) if callable(format_method) : for k, v in values.items() : values[k] = format_method(v, cell_name=k) else : LOG("PDFForm", PROBLEM, 'format method (%r) is not callable' % format_method) data = str(self.data) pdftk = PDFTk() pdf =pdftk.fillFormWithDict(data, values) if self.__page_range__: compiled_tales = getEngine().compile(self.__page_range__) page_range = getEngine().getContext(context).evaluate(compiled_tales) if page_range : pdf = pdftk.catPages(pdf, page_range) if RESPONSE : RESPONSE.setHeader('Content-Type', 'application/pdf') RESPONSE.setHeader('Content-Length', len(pdf)) RESPONSE.setHeader('Content-Disposition', 'inline;filename="%s.pdf"' % (self.title_or_id())) return pdf
def isTALES(value): if value.strip(): try: getEngine().compile(value) except tales.CompilerError: raise InvalidTALESError return True
def __call__(self, value, *args, **kwargs): if type(value) != type([]) and type(value) != type(()): value=(value,) for expr in value: try: if expr.strip(): getEngine().compile(expr) except TALES.CompilerError, e: return 'TALES expression "%s" has errors.' % expr
def createExprContext(folder, issuetracker, object, **extra_namespaces): ''' An expression context provides names for TALES expressions. ''' #pm = getToolByName(portal, 'portal_membership') if object is None: object_url = '' else: object_url = object.absolute_url() #if pm.isAnonymousUser(): # member = None #else: # member = pm.getAuthenticatedMember() data = { 'object_url': object_url, 'folder_url': folder.absolute_url(), #'portal_url': portal.absolute_url(), 'object': object, 'folder': folder, #'portal': portal, 'issuetracker': issuetracker, 'nothing': None, 'request': getattr(folder, 'REQUEST', None), 'modules': SecureModuleImporter, #'member': member, 'here': object, } data.update(extra_namespaces) return getEngine().getContext(data)
def registerSlotExprType(): # Register the 'slot:' expression type. from Products.PageTemplates.Expressions import getEngine # Avoid registering twice. engine = getEngine() if not engine.getTypes().has_key('slot'): engine.registerType('slot', SlotExpr)
def canBeCreatedInLicence(self, obj): """ Creation condition computed by evaluating the TAL expression stored in TALCondition field """ res = True # At least for now # Check condition TALCondition = self.getTALCondition().strip() if TALCondition: data = { 'nothing': None, 'portal': api.portal.get(), 'object': obj, 'event': self, 'request': api.portal.getRequest(), 'here': obj, 'licence': obj, } ctx = getEngine().getContext(data) try: res = Expression(TALCondition)(ctx) except Exception, e: logger.warn( "The condition '%s' defined for element at '%s' is wrong! Message is : %s" % (TALCondition, obj.absolute_url(), e)) res = False
def evaluateCell(self, cell_name, REQUEST=None, **kwargs): """ evaluate the TALES expression for this cell """ cell_name = str(cell_name) # we don't pass empty strings in TALES engine # (and this also raises the KeyError for non existant cells) if not self.cells[cell_name] : return None context = { 'here' : self.aq_parent, 'context' : self.aq_parent, 'cell_name' : cell_name, 'request' : REQUEST } context.update (kwargs) __traceback_info__ = 'Evaluating cell "%s"' % cell_name compiled_tales = getEngine().compile(self.cells[cell_name]) value = getEngine().getContext(context).evaluate(compiled_tales) return value
def createExprContext(folder, portal, object): ''' An expression context provides names for TALES expressions. ''' try: mtool = getUtility(IMembershipTool) except ComponentLookupError: # BBB: fallback for CMF 2.2 instances mtool = aq_get(portal, 'portal_membership') if object is None: object_url = '' else: object_url = object.absolute_url() if mtool.isAnonymousUser(): member = None else: member = mtool.getAuthenticatedMember() data = { 'object_url': object_url, 'folder_url': folder.absolute_url(), 'portal_url': portal.absolute_url(), 'object': object, 'folder': folder, 'portal': portal, 'nothing': None, 'request': getattr(portal, 'REQUEST', None), 'modules': SecureModuleImporter, 'member': member, 'here': object, } return getEngine().getContext(data)
def createExprContext(obj, **kw): """ Provides names for TALES expressions. """ if obj is None: object_url = '' else: object_url = obj.absolute_url() user = getSecurityManager().getUser() data = { 'object_url': object_url, 'object': obj, 'nothing': None, 'request': getattr(obj, 'REQUEST', None), 'modules': SecureModuleImporter, 'user': user, } if 'mimetype' in kw and not 'content_type' in kw: # Alias content_type to mimetype kw['content_type'] = kw['mimetype'] data.update(kw) for k in ('filename', 'content_type', 'data', 'mimetype'): data.setdefault(k, None) return getEngine().getContext(data)
def talesEval(express, context, extra=None): """Perform a TALES eval on the express using context. """ try: compiled = talesCompile(express) except Exception as e: compiled = talesCompile("string:%s" % express) contextDict = { 'context':context, 'here':context, 'nothing':None, 'now': DateTime(), } if isinstance(extra, dict): contextDict.update(extra) try: contextDict['info'] = IInfo(context) except TypeError: pass try: res = compiled(getEngine().getContext(contextDict)) except Exception, e: msg = "Error when processing tales expression %s on context %s : Exception Class %s Message: %s" % (express, context, type(e), e) raise InvalidTalesException(msg)
def __call__(self, value, *args, **kw): gen = TALGenerator(getEngine(), xml=1, source_file=None) parser = HTMLTALParser(gen) try: parser.parseString(value) except Exception, err: return ("Validation Failed(%s): \n %s" % (self.name, err))
def createCPContext(content, view_method, keywords, time=None): """ Construct an expression context for TALES expressions, for use by CachingPolicy objects. """ pm = getToolByName(content, 'portal_membership', None) if not pm or pm.isAnonymousUser(): member = None else: member = pm.getAuthenticatedMember() if time is None: time = DateTime() # The name "content" is deprecated and will go away in CMF 1.7, # please use "object" in your policy data = { 'content': content, 'object': content, 'view': view_method, 'keywords': keywords, 'request': getattr(content, 'REQUEST', {}), 'member': member, 'modules': SecureModuleImporter, 'nothing': None, 'time': time } return getEngine().getContext(data)
def createExprContext(sci): ''' An expression context provides names for TALES expressions. ''' ob = sci.object wf = sci.workflow container = aq_parent(aq_inner(ob)) data = { 'here': ob, 'object': ob, 'container': container, 'folder': container, 'nothing': None, 'root': wf.getPhysicalRoot(), 'request': getattr(ob, 'REQUEST', None), 'modules': SecureModuleImporter, 'user': getSecurityManager().getUser(), 'state_change': sci, 'transition': sci.transition, 'status': sci.status, 'kwargs': sci.kwargs, 'workflow': wf, 'scripts': wf.scripts, } return getEngine().getContext(data)
def getCommand(self, context, cmd=None): """Return localized command target. """ # Perform a TALES eval on the expression using self if cmd is None: cmd = self.commandTemplate if not cmd.startswith('string:') and not cmd.startswith('python:'): cmd = 'string:%s' % cmd compiled = talesCompile(cmd) d = context.device() environ = { 'dev': d, 'device': d, 'devname': d.id, 'ds': self, 'datasource': self, 'here': context, 'zCommandPath': context.zCommandPath, 'nothing': None, 'now': DateTime() } res = compiled(getEngine().getContext(environ)) if isinstance(res, Exception): raise res res = self.checkCommandPrefix(context, res) return res
def createExprContext(sci): ''' An expression context provides names for TALES expressions. ''' ob = sci.object wf = sci.workflow container = aq_parent(aq_inner(ob)) data = { 'here': ob, 'object': ob, 'container': container, 'folder': container, 'nothing': None, 'root': ob.getPhysicalRoot(), 'request': getattr( ob, 'REQUEST', None ), 'modules': SecureModuleImporter, 'user': getSecurityManager().getUser(), 'state_change': sci, 'transition': sci.transition, 'status': sci.status, 'kwargs': sci.kwargs, 'workflow': wf, 'scripts': wf.scripts, } return getEngine().getContext(data)
def getCommand(self, context, cmd=None): # No getCommand in BasicDataSource - inherits from # SimpleRRDDataSource inherits from RRDDataSource # Duplicate getCommand from RRDDataSource and add stringToFind # Perform a TALES eval on the expression using self if cmd is None: cmd = self.commandTemplate log.debug(' Raw cmd is %s ' % (cmd)) if self.stringToFind: #Need to ensure any white space is wrapped in quotes cmd = cmd + ' "' + self.stringToFind + '"' log.debug(' cmd with stringToFind is %s ' % (cmd)) if not cmd.startswith('string:') and not cmd.startswith('python:'): cmd = 'string:%s' % cmd log.debug(' cmd after string check is %s ' % (cmd)) compiled = talesCompile(cmd) d = context.device() environ = {'dev' : d, 'device': d, 'devname': d.id, 'ds': self, 'datasource': self, 'here' : context, 'zCommandPath' : context.zCommandPath, 'nothing' : None, 'now' : DateTime() } log.debug(' environ is %s ' % (environ)) res = compiled(getEngine().getContext(environ)) log.debug(' res compiled engine is %s ' % (res)) if isinstance(res, Exception): raise res res = self.checkCommandPrefix(context, res) log.debug(' res to return is %s ' % (res)) return res
def cook(cls, source_file, text, engine, content_type): if engine is getEngine(): def sanitize(m): match = m.group(1) logger.info( 'skipped "<?python%s?>" code block in ' 'Zope 2 page template object "%s".', match, source_file) return '' text, count = re_match_pi.subn(sanitize, text) if count: logger.warning("skipped %d code block%s (not allowed in " "restricted evaluation scope)." % (count, 's' if count > 1 else '')) expression_types = cls.secure_expression_types else: expression_types = cls.expression_types # BBB: Support CMFCore's FSPagetemplateFile formatting if source_file is not None and source_file.startswith('file:'): source_file = source_file[5:] template = ChameleonPageTemplate( text, filename=source_file, keep_body=True, expression_types=expression_types, encoding='utf-8', extra_builtins=cls.extra_builtins, ) return cls(template), template.macros
def _evaluate(self, value, object): '''evaluate our expression property in a context containing *value*, *object*, 'index', 'catalog' and standard names.''' index = self._findIndex() catalog = index.aq_inner.aq_parent # ATT: do we need to go up an additional level? # work around bug in "aq_acquire" (has 'default' argument but ignores it) try: request = object.aq_acquire('REQUEST', default=None) except AttributeError: request = None try: container = object.aq_inner.aq_parent except AttributeError: container = None data = { 'value': value, 'index': index, 'catalog': catalog, 'object': object, 'here': object, # compatibility 'container': container, 'nothing': None, 'root': index.getPhysicalRoot(), #'request': object.aq_acquire('REQUEST',default=None), 'request': request, 'modules': SecureModuleImporter, 'user': getSecurityManager().getUser(), } context = getEngine().getContext(data) expr = self._getExpression() return expr(context)
def __call__(self, value, instance, *args, **kwargs): kw={ 'here':instance, 'object':instance, 'instance':instance, 'value':value, 'args':args, 'kwargs':kwargs, } context=getEngine().getContext(kw) res=self.compiledExpression(context) if res: return True else: if self.errormsg and type(self.errormsg) == Message: #hack to support including values in i18n message, too. hopefully this works out #potentially it could unintentionally overwrite already present values self.errormsg.mapping = kw return recursiveTranslate(self.errormsg, **kwargs) elif self.errormsg: # support strings as errormsg for backward compatibility return self.errormsg % kw else: msg = _(u'validation failed, expr was:$expr', mapping={'expr': safe_unicode(self.expression)}) return recursiveTranslate(msg, **kwargs)
def talesEval(express, context, extra=None): """Perform a TALES eval on the express using context. """ try: compiled = talesCompile(express) except Exception as e: compiled = talesCompile("string:%s" % express) contextDict = { 'context': context, 'here': context, 'nothing': None, 'now': DateTime(), } if isinstance(extra, dict): contextDict.update(extra) try: contextDict['info'] = IInfo(context) except TypeError: pass try: res = compiled(getEngine().getContext(contextDict)) except Exception, e: msg = "Error when processing tales expression %s on context %s : Exception Class %s Message: %s" % ( express, context, type(e), e) raise InvalidTalesException(msg)
def _evaluate(self,value,object): '''evaluate our expression property in a context containing *value*, *object*, 'index', 'catalog' and standard names.''' index= self._findIndex() catalog= index.aq_inner.aq_parent # ATT: do we need to go up an additional level? # work around bug in "aq_acquire" (has 'default' argument but ignores it) try: request= object.aq_acquire('REQUEST',default=None) except AttributeError: request= None try: container= object.aq_inner.aq_parent except AttributeError: container= None data= { 'value' : value, 'index' : index, 'catalog' : catalog, 'object' : object, 'here' : object, # compatibility 'container' : container, 'nothing' : None, 'root' : index.getPhysicalRoot(), #'request': object.aq_acquire('REQUEST',default=None), 'request': request, 'modules' : SecureModuleImporter, 'user' : getSecurityManager().getUser(), } context= getEngine().getContext(data) expr= self._getExpression() return expr(context)
def createCPContext( content, view_method, keywords, time=None ): """ Construct an expression context for TALES expressions, for use by CachingPolicy objects. """ pm = getToolByName( content, 'portal_membership', None ) if not pm or pm.isAnonymousUser(): member = None else: member = pm.getAuthenticatedMember() if time is None: time = DateTime() # The name "content" is deprecated and will go away in CMF 1.7, # please use "object" in your policy data = { 'content' : content , 'object' : content , 'view' : view_method , 'keywords' : keywords , 'request' : getattr( content, 'REQUEST', {} ) , 'member' : member , 'modules' : SecureModuleImporter , 'nothing' : None , 'time' : time } return getEngine().getContext( data )
def createExprContext(folder, portal, object): ''' An expression context provides names for TALES expressions. ''' pm = getToolByName(portal, 'portal_membership') if object is None: object_url = '' else: object_url = object.absolute_url() if pm.isAnonymousUser(): member = None else: member = pm.getAuthenticatedMember() data = { 'object_url': object_url, 'folder_url': folder.absolute_url(), 'portal_url': portal.absolute_url(), 'object': object, 'folder': folder, 'portal': portal, 'nothing': None, 'request': getattr(portal, 'REQUEST', None), 'modules': SecureModuleImporter, 'member': member, 'here': object, } return getEngine().getContext(data)
def getCommand(self, context, cmd=None, device=None): """Return localized command target. """ # Perform a TALES eval on the expression using self if cmd is None: cmd = self.commandTemplate if not cmd.startswith('string:') and not cmd.startswith('python:'): cmd = 'string:%s' % cmd compiled = talesCompile(cmd) d = device if device is not None else context.device() environ = {'dev' : d, 'device': d, 'devname': d.id, 'ds': self, 'datasource': self, 'here' : context, 'context': context, 'zCommandPath' : context.zCommandPath, 'nothing' : None, 'now' : DateTime() } res = compiled(getEngine().getContext(environ)) if isinstance(res, Exception): raise res res = self.checkCommandPrefix(context, res) return res
def createExprContext(folder, portal, object): ''' An expression context provides names for TALES expressions. ''' pm = getToolByName(portal, 'portal_membership') if object is None: object_url = '' else: object_url = object.absolute_url() if pm.isAnonymousUser(): member = None else: member = pm.getAuthenticatedMember() data = { 'object_url': object_url, 'folder_url': folder.absolute_url(), 'portal_url': portal.absolute_url(), 'object': object, 'folder': folder, 'portal': portal, 'nothing': None, 'request': getattr( object, 'REQUEST', None ), 'modules': SecureModuleImporter, 'member': member, } return getEngine().getContext(data)
def createExprContext(folder, portal, object): """ An expression context provides names for TALES expressions. """ try: mtool = getUtility(IMembershipTool) except ComponentLookupError: # BBB: fallback for CMF 2.2 instances mtool = aq_get(portal, 'portal_membership') if object is None: object_url = '' else: object_url = object.absolute_url() if mtool.isAnonymousUser(): member = None else: member = mtool.getAuthenticatedMember() data = { 'object_url': object_url, 'folder_url': folder.absolute_url(), 'portal_url': portal.absolute_url(), 'object': object, 'folder': folder, 'portal': portal, 'nothing': None, 'request': getattr(portal, 'REQUEST', None), 'modules': SecureModuleImporter, 'member': member, 'here': object, } return getEngine().getContext(data)
def _getExpression(self): '''return the TALES expression to be evaluated.''' expr= self._v_expression expr_string= self.aq_acquire(self.ExpressionProperty) if expr != 0 and self._v_expr_string == expr_string: return expr expr= self._v_expression= getEngine().compile(expr_string) self._v_expr_string= expr_string return expr
def create_tal_context(view, **kw): data = dict(context=view.context, here=view.context, nothing=None, request=view.request, view=view) data.update(kw) return getEngine().getContext(data)
def __call__(self, econtext): compiled = self._v_compiled if compiled is None: compiled = self._v_compiled = getEngine().compile(self._text) res = compiled(econtext) if isinstance(res, Exception): raise res return res
def _getExpression(self): '''return the TALES expression to be evaluated.''' expr = self._v_expression expr_string = self.aq_acquire(self.ExpressionProperty) if expr != 0 and self._v_expr_string == expr_string: return expr expr = self._v_expression = getEngine().compile(expr_string) self._v_expr_string = expr_string return expr
def __call__(self, econtext): compiled = self._v_compiled if compiled is None: compiled = self._v_compiled = getEngine().compile(self.text) res = compiled(econtext) if isinstance(res, Exception): raise res return res
def __call__(self, econtext): compiled = self._v_compiled if compiled is None: compiled = self._v_compiled = getEngine().compile(self.text) # ?? Maybe expressions should manipulate the security # context stack. res = compiled(econtext) if isinstance(res, Exception): raise res return res
def testGetSelectionParamsDictInterface(self): self.assertEquals("value", self.portal_selections["test_selection"]["key"]) # the main use case is to have a dict interface in TALES expressions: from Products.PageTemplates.Expressions import getEngine evaluate_tales = getEngine().getContext(dict(context=self.portal)).evaluate self.assertEquals("value", evaluate_tales("context/portal_selections/test_selection/key")) self.assertEquals( "default", evaluate_tales("context/portal_selections/test_selection/not_found | string:default") )
def testGetSelectionParamsDictInterface(self): self.assertEqual('value', self.portal_selections['test_selection']['key']) # the main use case is to have a dict interface in TALES expressions: from Products.PageTemplates.Expressions import getEngine evaluate_tales = getEngine().getContext(dict(context=self.portal)).evaluate self.assertEqual('value', evaluate_tales('context/portal_selections/test_selection/key')) self.assertEqual('default', evaluate_tales( 'context/portal_selections/test_selection/not_found | string:default'))
def testCanAccessResultsFromRestrictedPython(self): # user without the SalesforceRead permission can't query expr = 'python:context.portal_salesforcebaseconnector.query("SELECT Id FROM Contact")[0]' engine = getEngine() econtext = engine.getContext({'context': self.portal}) self.assertRaises(Unauthorized, getEngine().compile(expr), econtext) # user with the SalesforceRead permission can query and access result self.setRoles(['Manager']) res = getEngine().compile(expr)(econtext) self.failUnless(len(res)) expr = 'python:context.portal_salesforcebaseconnector.query("SELECT Id FROM Contact")["records"][0]' res = getEngine().compile(expr)(econtext) self.failUnless(res) expr = 'python:context.portal_salesforcebaseconnector.query("SELECT Id FROM Contact")["records"][0]["Id"]' res = getEngine().compile(expr)(econtext) self.failUnless(res)
def __call__(self, econtext): compiled = self._v_compiled if compiled is None: compiled = self._v_compiled = getEngine().compile(self.text) # ?? Maybe expressions should manipulate the security # context stack. res = compiled(econtext) if isinstance(res, Exception): raise res #print 'returning %s from %s' % (`res`, self.text) return res
def exprNamespace(client=None, form=None, field=None, value=None, object=None): c = { 'form': form, 'field': field, 'value': value, 'here': object, 'nothing': None, 'options': {}, 'root': None, 'request': None, 'modules': SecureModuleImporter } return getEngine().getContext(c)
def __call__(self, econtext): if not self.text.strip(): return '' compiled = self._v_compiled if compiled is None: compiled = self._v_compiled = getEngine().compile(self.text) # ?? Maybe expressions should manipulate the security # context stack. res = compiled(econtext) if isinstance(res, Exception): raise res return res
def getFilterExprContext(object_memento, portal): data = { 'portal_url': portal.absolute_url(), 'memento': object_memento, 'portal': portal, 'nothing': None, 'request': getattr( portal, 'REQUEST', None ), 'modules': SecureModuleImporter, } return getEngine().getContext(data)
def createExprContext( object): ''' An expression context provides names for TALES expressions. ''' data = { 'object': object, 'nothing': None, 'request': getattr( object, 'REQUEST', None ), 'modules': SecureModuleImporter, } return getEngine().getContext(data)
def getDeployExprContext(object, portal): data = { 'object': object, 'portal': portal, 'nothing': None, 'request': getattr( object, 'REQUEST', None ), 'modules': SecureModuleImporter, 'deploy': DeploymentMimeUtilities.__of__(object) } return getEngine().getContext(data)
def exprNamespace(instance, workitem=None, activity=None, process=None, openflow=None): c = { 'instance': instance, 'workitem' : workitem, 'activity' : activity, 'process' : process, 'openflow' : openflow, 'here': instance, 'nothing': None, 'options': {}, 'request': getattr(instance, 'REQUEST', None), 'modules': SecureModuleImporter } return getEngine().getContext(c)
def getActionContext( self ): data = { 'object_url' : '' , 'folder_url' : '' , 'portal_url' : '' , 'object' : None , 'folder' : None , 'portal' : None , 'nothing' : None , 'request' : getattr( self, 'REQUEST', None ) , 'modules' : SecureModuleImporter , 'member' : None } return getEngine().getContext( data )
def getNormalUrl(self, portal_type, url): action_map = getattr(self, '_preview_actions', {}) if portal_type in action_map: expr = action_map[portal_type].get('normal', None) if expr: data = { 'object_url': url, 'portal_type': portal_type, 'modules': SecureModuleImporter, } context = getEngine().getContext(data) return expr(context) return url
def _patched_cook(cls, source_file, text, engine, content_type): if engine is getEngine(): # Same as in chameleon/parser.py, but without the leading '^' for # the beginning of the text. And we explicitly look for python, # mostly to avoid matching '<?xml...' match_processing_instruction = re.compile( r'<\?python(?P<text>.*?)\?>', re.DOTALL) matches = match_processing_instruction.findall(text) if matches: for match in matches: logger.warn( 'Ignored "<?python" expression %r in ' 'Zope 2 page template at %s', match, source_file) text = match_processing_instruction.sub('', text) return cls._original_cook(source_file, text, engine, content_type)
def createExprContext(element, ob): ''' An expression context provides names for TALES expressions. ''' data = { 'here': ob, 'container': aq_parent(aq_inner(ob)), 'nothing': None, 'element': element, 'request': getattr(ob, 'REQUEST', None), 'modules': SecureModuleImporter, 'user': getSecurityManager().getUser(), } return getEngine().getContext(data)
def getActionContext( self ): # getActionContext is deprecated and will be removed in CMF 1.6. # This is only used by the deprecated _getViewFor function and the # deprecated getActionById method. data = { 'object_url' : '' , 'folder_url' : '' , 'portal_url' : '' , 'object' : None , 'folder' : None , 'portal' : None , 'nothing' : None , 'request' : getattr( self, 'REQUEST', None ) , 'modules' : SecureModuleImporter , 'member' : None } return getEngine().getContext( data )
def getActionContext( self ): # getActionContext is deprecated and will be removed as soon as the # backwards compatibility code in TypeInformation._guessMethodAliases is # removed. data = { 'object_url' : '' , 'folder_url' : '' , 'portal_url' : '' , 'object' : None , 'folder' : None , 'portal' : None , 'nothing' : None , 'request' : getattr( self, 'REQUEST', None ) , 'modules' : SecureModuleImporter , 'member' : None } return getEngine().getContext( data )
def compile(self, cmd, target): ''' Evaluate command as a tales expression ''' command = cmd.command # make sure we are targeting the right collector if not command.startswith("dcsh") and hasattr(target, "getPerformanceServerName"): collector = target.getPerformanceServer() # if there isn't a collector just run it locally if collector and hasattr(collector, 'isLocalHost') and not collector.isLocalHost(): command = 'dcsh --collector=${device/getPerformanceServerName} -n "%s"' % (command.replace('\n', ' ')) exp = "string:"+ command compiled = talesCompile(exp) environ = target.getUserCommandEnvironment() res = compiled(getEngine().getContext(environ)) if isinstance(res, Exception): raise res return res
def get_zope_page_template_engine(engine): """Get Zope-aware page template engine. Hopefully a trusted one, but maybe an untrusted one, with less possibilities and more security checks. We fall back to nothing. This means the original engine will be used. Needed since the page template refactoring/cleanup in Zope 4.4. See https://github.com/plone/Products.CMFPlone/issues/3141 This is currently expected to only be called when a zope.pagetemplate is being rendered, which can happen with z3c.form related code. For Products.PageTemplates, this code should not be needed. """ if isinstance(engine, zpt_engine.ZopeEngine): # Get untrusted engine. return getEngine() if isinstance(engine, zpt_engine.TrustedZopeEngine): return getTrustedEngine()