def updateScript(self, body):
        # Regenerate Python script object

        # Sync set of script source code and
        # creation of Python Script object.

        bodyField = self.schema["mipago_payment_amountOverride"]
        script = PythonScript(self.title_or_id())
        script = script.__of__(self)

        script.ZPythonScript_edit("fields, ploneformgen, request", body)

        PythonField.set(bodyField, self, script)
    def updateScript(self, body, role):
        # Regenerate Python script object

        # Sync set of script source code, proxy role and
        # creation of Python Script object.

        bodyField = self.schema["ScriptBody"]
        proxyField = self.schema["ProxyRole"]
        script = PythonScript(self.title_or_id())
        script = script.__of__(self)

        # Force proxy role
        if role != "none":
            script.manage_proxy((role,))

        script.ZPythonScript_edit("fields, ploneformgen, request", body)

        PythonField.set(bodyField, self, script)
        StringField.set(proxyField, self, role)
Example #3
0
    def updateScript(self, body, role):
        # Regenerate Python script object

        # Sync set of script source code, proxy role and
        # creation of Python Script object.

        bodyField = self.schema["ScriptBody"]
        proxyField = self.schema["ProxyRole"]
        script = PythonScript(self.title_or_id())
        script = script.__of__(self)

        # Force proxy role
        if role != "none":
            script.manage_proxy((role, ))

        script.ZPythonScript_edit("fields, ploneformgen, request", body)

        PythonField.set(bodyField, self, script)
        StringField.set(proxyField, self, role)
Example #4
0
 def afterSetUp(self):
     from Products.PythonField import PythonField
     self.field = PythonField('python')
     self.folder.validate_field = lambda *args, **kw: None
Example #5
0
class PythonFieldTest(PloneTestCase.PloneTestCase):

    def afterSetUp(self):
        from Products.PythonField import PythonField
        self.field = PythonField('python')
        self.folder.validate_field = lambda *args, **kw: None

    def validate(self, value):
        errors = {}
        res = self.field.validate(value, self.folder, errors)
        return res, errors

    def test_defaults(self):
        self.assertEquals(self.field.get(self.folder), None)

    def test_getRaw(self):
        raw = self.field.getRaw(self.folder)
        self.assertEquals(raw, 'pass\n')

    def test_set(self):
        self.assertEquals(self.field.get(self.folder), None)
        self.folder.setTitle('bar')
        self.field.set(self.folder, "return context.Title() == 'foo'")
        self.assertEquals(self.field.get(self.folder), False)
        self.field.set(self.folder, "return context.Title() == 'bar'")
        self.assertEquals(self.field.get(self.folder), True)

    def test_set_pythonscript(self):
        # Just make sure setting PythonScript works too.
        default_script = self.field.getDefault(self.folder)
        self.field.set(self.folder, default_script)
        self.assertEquals(
            self.field.getRaw(self.folder), default_script.body())

    def test_validate(self):
        self.assertEquals(self.validate('True'), (None, {}))
        self.assertEquals(
            self.validate('1 + (2 * 3'),
            ('unexpected EOF while parsing (Script (Python), line 1)', {}))

    def test_header_footer(self):
        self.field.header = "foo = 'bar'"
        self.field.footer = "return foo"
        self.field.set(self.folder, "pass")
        self.assertEquals(self.field.get(self.folder), 'bar')
        self.field.set(self.folder, "foo = 'baz'")
        self.assertEquals(self.field.get(self.folder), 'baz')
        self.assertEquals(self.field.getRaw(self.folder), "foo = 'baz'\n")
Example #6
0
 def afterSetUp(self):
     PloneTestCase.PloneTestCase.afterSetUp(self)
     self.field = PythonField('python')
     self.folder.validate_field = lambda *args, **kw: None
class FormCustomScriptAdapter(FormActionAdapter):
    """ Executes a Python script for form data
    """

    # Python script receives parameters 
    #     resultData  - cleaned up input
    #     form        - the PFG object
    #     REQUEST
    
    # External Python script (as in Plone skins)
    SCRIPT_TYPE_SKINS_SCRIPT="skins_script"
    
    # Script defined in ScriptData field
    SCRIPT_TYPE_INTERNAL_SCRIPT="internal_script"

    schema = FormAdapterSchema.copy() + Schema((
        StringField('ProxyRole',
            searchable=0,
            required=1,
            default="none",
            read_permission=ModifyPortalContent,
            write_permission=EDIT_PYTHON_PERMISSION,
            vocabulary="getProxyRoleChoices",
            widget=SelectionWidget(
                label=_(u'label_script_proxy', default=u'Proxy role'),
                description = _(u'help_script_proxy', default=u""" Role under which to run the script. """),
                ),
            ),            
     
        PythonField('ScriptBody',
            searchable=0,
            required=0,
            default=default_script,
            read_permission=ModifyPortalContent,
            write_permission=EDIT_PYTHON_PERMISSION,
            widget=TextAreaWidget(
                label=_(u'label_script_body', default=u'Script body'),
                rows=10,
                visible={'view': 'invisible','edit': 'visible'},    
                description = _(u'help_script_body', default=u""" Write your script here. """),
                ),
            ),            
    ))

    meta_type = portal_type = 'FormCustomScriptAdapter'
    archetype_name = 'Custom Script Adapter'

    content_icon   = 'scriptaction.gif'

    #immediate_view = 'fg_savedata_view'
    #default_view   = 'fg_savedata_view'

    security = ClassSecurityInfo()
    
    def __init__(self, oid, **kwargs):
        """ initialize class """

        FormActionAdapter.__init__(self, oid, **kwargs)
        
        # for the convenience of scripters operating
        # in a restricted python environment,
        # let's store a reference to FORM_ERROR_MARKER
        # on the object, so it'll be available
        # as an attribute of context.
        self.FORM_ERROR_MARKER = config.FORM_ERROR_MARKER
    
    def updateScript(self, body, role):
        """ Regenerate Python script object 
        
        Sync set of script source code, proxy role and 
        creation of Python Script object.
        
        """         
        bodyField = self.schema["ScriptBody"]    
        proxyField = self.schema["ProxyRole"]    
        script = PythonScript(self.title_or_id())
        script = script.__of__(self)
        
        # Force proxy role     
        if role != "none":
            script.manage_proxy((role,))
        
        script.ZPythonScript_edit("fields, ploneformgen, request", body)            
                
        PythonField.set(bodyField, self, script)        
        StringField.set(proxyField, self, role)
            
    def setScriptBody(self, body):
        """ Make PythonScript construction to take parameters """    
        proxy = self.getProxyRole()        
        self.updateScript(body, proxy)
                
    def setProxyRole(self, role):
        sourceCode = self.getRawScriptBody()
        self.updateScript(sourceCode, role)
        
    def getProxyRoleChoices(self):
        """ Get proxy role choices"""
        
        # XXX TODO: use real role list
        return DisplayList(
           (("none", "No proxy role"),
            ("Manager", "Manager"),
            ))
                
    def onSuccess(self, fields, REQUEST=None):
        """ Executes the custom script
        
        """
                        
        # use PloneFormGen object as a context
        form = aq_parent(self)       
        
        if REQUEST != None:
            resultData = self.sanifyFields(REQUEST.form) 
        else:
            resultData = {}
                        
        return self.executeCustomScript(resultData, form, REQUEST)
        
    def checkWarningsAndErrors(self):
        """ Raise exception if there has been bad things with the script compiling """
        field = self.schema["ScriptBody"]      
                  
        script = ObjectField.get(field, self)
        
        if len(script.warnings) > 0:
            logger.warn("Python script " + self.title_or_id() + " has warning:" + str(script.warnings))
        
        if len(script.errors) > 0:
            logger.error("Python script "  + self.title_or_id() +  " has errors: " + str(script.errors))
            raise ValueError, "Python script "  + self.title_or_id() + " has errors: " + str(script.errors)
    
    def executeCustomScript(self, result, form, req):
        """ Execute in-place script  
        
        @param result Extracted fields from REQUEST.form
        @param form PloneFormGen object
        """        
        field = self.schema["ScriptBody"] 
        # Now pass through PythonField/PythonScript abstraction 
        # to access bad things (tm)
        # otherwise there are silent failures
        script = ObjectField.get(field, self)
                
        logger.debug("Executing Custom Script Adapter " + self.title_or_id() + " fields:" + str(result))
        
        self.checkWarningsAndErrors()        
                    
        response = script(result, form, req)    
        return response
    
    def sanifyFields(self, form):
        """ Makes request.form fields accessible in a script 
        
        Avoid Unauthorized exceptions since REQUEST.form is inaccesible
        """
        result = {}
        for field in form:
            result[field] = form[field]
        return result
        schemata='overrides',
        required=False,
        default=False,
        widget=atapi.BooleanWidget(label=_(
            'Check if you need to calculate the amount using a python script'),
                                   )),
    PythonField(
        'mipago_payment_amountOverride',
        schemata='overrides',
        searchable=0,
        required=0,
        default=default_script,
        write_permission=EDIT_PYTHON_PERMISSION,
        read_permission=ModifyPortalContent,
        isMetadata=True,  # just to hide from base view
        widget=atapi.TextAreaWidget(
            label=_(u'Amount calculation script'),
            rows=20,
            visible={
                'view': 'invisible',
                'edit': 'visible'
            },
            description=_(u'Write here the script that calculates the amount'),
        ),
    ),
))

# Hide unneeded fields coming from formMailerAdapter
MiPagoAdapterSchema['additional_headers'].widget.visible = {
    'view': 'invisible',
    'edit': 'invisible'