Esempio n. 1
0
    def displayInputs(self, request):
        """ Returns sequence of dicts {'label':fieldlabel, 'value':input}
        """

        # get a list of all candidate fields
        myFields = []
        for obj in self.aq_parent._getFieldObjects():
            if not (IField.isImplementedBy(obj) or obj.isLabel()):
                myFields.append(obj)

        # Now, determine which fields we show
        if self.showAll:
            sFields = myFields
        else:
            sFields = []
            # acquire field list from parent
            res = []
            for id in self.showFields:
                # inefficient if we get many fields
                for f in myFields:
                    if f.getId() == id:
                        sFields.append(f)
                        break

        # Now, build the results list
        res = []
        for obj in sFields:
            value = obj.htmlValue(request)
            if self.includeEmpties or (value and (value != 'No Input')):
                res.append( {
                    'label' : obj.fgField.widget.label,
                    'value' : value, 
                    } )
            
        return res
Esempio n. 2
0
    def __call__(self):
        box = self.context.get_box()
        secret = self.request.form.get('secret')
        email = self.request.form.get('email')
        data = box.pop(secret, token=email)

        if data is None:
            return self.index()

        form = self.context.get_form()
        fields = [fo for fo in form._getFieldObjects()
                  if not IField.providedBy(fo)]

        # Put the data in the request.  Make it a dictionary,
        # otherwise the fg_result_view does not work, as an anonymous
        # user is not authorized to get items from the data, as it is
        # a PersistentMapping.
        self.request.form = dict(data)
        self.context.send_form(fields, self.request)

        # Get the thank you page.
        thankspage = self.context.thanksPage
        if not thankspage:
            thankspage = form.thanksPage
        thanks = form.get(thankspage)
        if thanks is None:
            thanks = form.unrestrictedTraverse('fg_result_view')
        return thanks()
    def fgFields(self, request=None, displayOnly=False,
                 excludeServerSide=True):
        """ generate fields on the fly; also primes request with
            defaults if request is passed.
            if displayOnly, label fields are excluded.
        """

        self.fgMaybeForceSSL()

        if request and self.getRawOnDisplayOverride():
            # call the tales expression, passing a custom context
            self.getOnDisplayOverride()
            self.cleanExpressionContext(request=request)

        myFields = []
        for obj in self._getFieldObjects(includeFSMarkers=not displayOnly):
            if IField.providedBy(obj):
                # this is a field -- not a form field -- and may be
                # added directly to the field list.
                if not displayOnly:
                    myFields.append(obj)
            else:
                if request:
                    # prime the request
                    obj.fgPrimeDefaults(request)

                if not (displayOnly and obj.isLabel()) and \
                   not (excludeServerSide and obj.getServerSide()):
                    myFields.append(obj.fgField)

        return myFields
Esempio n. 4
0
 def testDateFieldConvertedToSalesforceFormat(self):
     """ Prove that DateField values get converted to the format
         expected by Salesforce (mm/dd/yyyy).
     """
     self.ff1.invokeFactory('FormDateField', 'date')
     self.ff1.date.setTitle('date')
     
     self.ff1.invokeFactory('SalesforcePFGAdapter', 'salesforce')
     self.ff1.setActionAdapter( ('salesforce',) )
     sf = self.ff1.salesforce
     
     fieldmap = sf.getFieldMap()
     fieldmap[-1]['sf_field'] = 'date'
     sf.setFieldMap(fieldmap)
     
     from DateTime import DateTime
     now = DateTime()
     now_plone = now.strftime('%m-%d-%Y %H:%M')
     
     request = FakeRequest(topic = 'test subject', replyto='*****@*****.**',
                           date = now_plone)
     from Products.Archetypes.interfaces.field import IField
     fields = [fo for fo in self.ff1._getFieldObjects() if not IField.isImplementedBy(fo)]
     sObject = self.ff1.salesforce._buildSObjectFromForm(fields, REQUEST=request)
     
     from time import strptime
     try:
         res = strptime(sObject['date'], '%Y-%m-%dT%H:%M:%SZ')
     except ValueError:
         self.fail("Doesn't look like the date was converted to Salesforce format properly.")
Esempio n. 5
0
    def fgFields(self, request=None, displayOnly=False,
                 excludeServerSide=True):
        """ generate fields on the fly; also primes request with
            defaults if request is passed.
            if displayOnly, label fields are excluded.
        """

        self.fgMaybeForceSSL()

        if request and self.getRawOnDisplayOverride():
            # call the tales expression, passing a custom context
            self.getOnDisplayOverride()
            self.cleanExpressionContext(request=request)

        myFields = []
        for obj in self._getFieldObjects(includeFSMarkers=not displayOnly):
            if IField.providedBy(obj):
                # this is a field -- not a form field -- and may be
                # added directly to the field list.
                if not displayOnly:
                    myFields.append(obj)
            else:
                if request:
                    # prime the request
                    obj.fgPrimeDefaults(request)

                if not (displayOnly and obj.isLabel()) and \
                   not (excludeServerSide and obj.getServerSide()):
                    myFields.append(obj.fgField)

        return myFields
Esempio n. 6
0
File: form.py Progetto: dtgit/dtedu
    def fgFields(self, request=None, displayOnly=False):
        """ generate fields on the fly; also primes request with
            defaults if request is passed.
            if displayOnly, label fields are excluded.
        """

        if request and self.getRawOnDisplayOverride():
            # call the tales expression, passing a custom context
            #self.getOnDisplayOverride(expression_context=getExprContext(self, self.aq_explicit))
            self.getOnDisplayOverride()
            self.cleanExpressionContext(request=request)

        myFields = []
        for obj in self._getFieldObjects(includeFSMarkers=not displayOnly):
            if IField.isImplementedBy(obj):
                # this is a field -- not a form field -- and may be
                # added directly to the field list.
                if not displayOnly:
                    myFields.append(obj)
            else:
                if request:
                    # prime the request
                    obj.fgPrimeDefaults(request)
                #if not (displayOnly and (obj.isLabel() or obj.isFileField()) ):
                if not (displayOnly and obj.isLabel()):
                    myFields.append(obj.fgField)

        return myFields
def finalize_registrant_creation(obj, event):
    """
    we are using a type created from uwosh FormSaveData2ContentEntry.
    So we need to get it by interface to cath the event, but here we need to
    check on portal_type, 'cause all the type created by uwosh stuff implements
    IFormSaveData2ContentEntry
    """
    # change the object state
    if obj.portal_type == 'registrant':
        site = getSite()
        portal_workflow = getToolByName(site, 'portal_workflow')
        portal_membership = getToolByName(site, 'portal_membership')
        current_state = portal_workflow.getInfoFor(obj, 'review_state')
        if current_state in ('new', ):
            signupsheet = obj.getForm()
            action = compute_next_action(obj, signupsheet)
            portal_workflow.doActionFor(obj, action)

        if portal_membership.isAnonymousUser():
            obj.setCreators(('(anonymous)',))

        #Simulate mailer action
        #we want send also information about review state and we want mailer do
        #all the job
        form = obj.getForm()
        adapter = getattr(form.aq_explicit, 'user_notification_mailer', None)
        fields = [fo for fo in obj.getForm()._getFieldObjects()
                                          if not IField.providedBy(fo)]
        obj.REQUEST['review_state'] = \
                signupsheetMessageFactory(unicode(portal_workflow.getInfoFor(obj,
                                                                             'review_state')))
        # If we are importing registrants from csv file, this flag allow to decide
        # to send or not notification mail
        if 'avoid_mail_notification' not in obj.REQUEST.form:
            adapter.onSuccess(fields, obj.REQUEST)
Esempio n. 8
0
 def _validateOnAdd(self, field):
     """Validates fields on adding and bootstrapping
     """
     # interface test
     if not IField.providedBy(field):
         raise ValueError, "Object doesn't implement IField: %r" % field
     name = field.getName()
     # two primary fields are forbidden
     if getattr(field, 'primary', False):
         res = self.hasPrimary()
         if res is not False and name != res.getName():
             raise SchemaException(
                 "Tried to add '%s' as primary field "
                 "but %s already has the primary field '%s'." %
                 (name, repr(self), res.getName())
             )
     for pname in ('accessor', 'edit_accessor', 'mutator'):
         res = self._checkPropertyDupe(field, pname)
         if res is not False:
             res, value = res
             raise SchemaException(
                 "Tried to add '%s' with property '%s' set "
                 "to %s but '%s' has the same value." %
                 (name, pname, repr(value), res.getName())
             )
     # Do not allowed unqualified references
     if field.type in ('reference', ):
         relationship = getattr(field, 'relationship', '')
         if type(relationship) is not StringType or len(relationship) == 0:
             raise ReferenceException(
                 "Unqualified relationship or "
                 "unsupported relationship var type in field '%s'. "
                 "The relationship qualifer must be a non empty "
                 "string." % name
             )
Esempio n. 9
0
 def _validateOnAdd(self, field):
     """Validates fields on adding and bootstrapping
     """
     # interface test
     if not IField.providedBy(field):
         raise ValueError, "Object doesn't implement IField: %r" % field
     name = field.getName()
     # two primary fields are forbidden
     if getattr(field, 'primary', False):
         res = self.hasPrimary()
         if res is not False and name != res.getName():
             raise SchemaException(
                 "Tried to add '%s' as primary field "
                 "but %s already has the primary field '%s'." %
                 (name, repr(self), res.getName()))
     for pname in ('accessor', 'edit_accessor', 'mutator'):
         res = self._checkPropertyDupe(field, pname)
         if res is not False:
             res, value = res
             raise SchemaException(
                 "Tried to add '%s' with property '%s' set "
                 "to %s but '%s' has the same value." %
                 (name, pname, repr(value), res.getName()))
     # Do not allowed unqualified references
     if field.type in ('reference', ):
         relationship = getattr(field, 'relationship', '')
         if type(relationship) is not StringType or len(relationship) == 0:
             raise ReferenceException(
                 "Unqualified relationship or "
                 "unsupported relationship var type in field '%s'. "
                 "The relationship qualifer must be a non empty "
                 "string." % name)
Esempio n. 10
0
    def fgProcessActionAdapters(self, errors, fields=None, REQUEST=None):
        if fields is None:
            fields = [fo for fo in self._getFieldObjects()
                      if not IField.providedBy(fo)]

        if not errors:
            if self.getRawAfterValidationOverride():
                # evaluate the override.
                # In case we end up traversing to a template,
                # we need to make sure we don't clobber
                # the expression context.
                self.getAfterValidationOverride()
                self.cleanExpressionContext(request=self.REQUEST)

            # get a list of adapters with no duplicates, retaining order
            adapters = []
            for adapter in self.getRawActionAdapter():
                if adapter not in adapters:
                    adapters.append(adapter)

            for adapter in adapters:
                actionAdapter = getattr(self.aq_explicit, adapter, None)
                if actionAdapter is None:
                    logger.warn(
                      "Designated action adapter '%s' is missing; ignored. "
                      "Removing it from active list." %
                      adapter)
                    self.toggleActionActive(adapter)
                else:
                    # Now, see if we should execute it.
                    # If using the 'finalise' workflow, only trigger
                    # 'save data' adapters
                    if self.getUseFinaliseButton() \
                        and 'form_finalise' not in REQUEST:
                        if not IStatefulActionAdapter.providedBy(actionAdapter):
                            # skip it
                            continue

                    # Check to see if execCondition exists and has contents
                    if safe_hasattr(actionAdapter, 'execCondition') and \
                      len(actionAdapter.getRawExecCondition()):
                        # evaluate the execCondition.
                        # create a context for expression evaluation
                        context = getExprContext(self, actionAdapter)
                        doit = actionAdapter.getExecCondition(
                          expression_context=context)
                    else:
                        # no reason not to go ahead
                        doit = True

                    if doit:
                        result = actionAdapter.onSuccess(fields, \
                                                         REQUEST=REQUEST)
                        if type(result) is type({}) and len(result):
                            # return the dict, which hopefully uses
                            # field ids or FORM_ERROR_MARKER for keys
                            return result

        return errors
Esempio n. 11
0
 def replaceField(self, name, field):
     if IField.providedBy(field):
         oidx = self._names.index(name)
         new_name = field.getName()
         self._names[oidx] = new_name
         del self._fields[name]
         self._fields[new_name] = field
     else:
         raise ValueError, "Object doesn't implement IField: %r" % field
Esempio n. 12
0
 def replaceField(self, name, field):
     if IField.providedBy(field):
         oidx = self._names.index(name)
         new_name = field.getName()
         self._names[oidx] = new_name
         del self._fields[name]
         self._fields[new_name] = field
     else:
         raise ValueError, "Object doesn't implement IField: %r" % field
Esempio n. 13
0
    def fgProcessActionAdapters(self, errors, fields=None, REQUEST=None):
        if fields is None:
            fields = [
                fo for fo in self._getFieldObjects()
                if not IField.providedBy(fo)
            ]

        if not errors:
            if self.getRawAfterValidationOverride():
                # evaluate the override.
                # In case we end up traversing to a template,
                # we need to make sure we don't clobber
                # the expression context.
                self.getAfterValidationOverride()
                self.cleanExpressionContext(request=self.REQUEST)

            # get a list of adapters with no duplicates, retaining order
            adapters = []
            for adapter in self.getRawActionAdapter():
                if adapter not in adapters:
                    adapters.append(adapter)

            for adapter in adapters:
                actionAdapter = getattr(self.aq_explicit, adapter, None)
                if actionAdapter is None:
                    logger.warn(
                        "Designated action adapter '%s' is missing; ignored. "
                        "Removing it from active list." % adapter)
                    self.toggleActionActive(adapter)
                else:
                    # Now, see if we should execute it.
                    # Check to see if execCondition exists and has contents
                    if safe_hasattr(actionAdapter, 'execCondition') and \
                      len(actionAdapter.getRawExecCondition()):
                        # evaluate the execCondition.
                        # create a context for expression evaluation
                        context = getExprContext(self, actionAdapter)
                        doit = actionAdapter.getExecCondition(
                            expression_context=context)
                    else:
                        # no reason not to go ahead
                        doit = True

                    if doit:
                        result = actionAdapter.onSuccess(fields, \
                                                         REQUEST=REQUEST)
                        if type(result) is type({}) and len(result):
                            # return the dict, which hopefully uses
                            # field ids or FORM_ERROR_MARKER for keys
                            return result

        return errors
 def all_fields(self):
     context = aq_inner(self.context)
     fields = IAnnotations(context).get('collective.pfg.showrequest.fields')
     if fields is not None:
         objs = [(obj.id, obj) for obj in context._getFieldObjects()
                 if (not IField.providedBy(obj) or obj.isLabel())
                 and obj.id in fields]
         sorted_objs = []
         objs = dict(objs)
         for field in fields:
             sorted_objs.append(objs[field])
         res = []
         for obj in sorted_objs:
             value = obj.htmlValue(self.request)
             res.append({
                 'label': obj.fgField.widget.label,
                 'value': value,
             })
         return res
    def __call__(self):
        box = self.context.get_box()
        secret = self.request.form.get('secret')
        email = self.request.form.get('email')
        data = box.pop(secret, token=email)

        if data is None:
            return self.index()

        alsoProvides(self.request, IConfirmedSubmission)
        form = self.context.get_form()
        fields = [fo for fo in form._getFieldObjects()
                  if not IField.providedBy(fo)]

        # Put the data in the request.  Make it a dictionary,
        # otherwise the fg_result_view does not work, as an anonymous
        # user is not authorized to get items from the data, as it is
        # a PersistentMapping.
        self.request.form = dict(data)

        # Send mail that would be send when this would have been
        # a standard FormMailerAdapter.
        if self.context.send_standard_mail:
            self.context.send_form(fields, self.request)

        # Process the other adapters.  First argument is 'errors'.
        result = form.fgProcessActionAdapters(
            {}, fields=fields, REQUEST=self.request)
        if result:
            # We have an error.  Abort any changes.
            transaction.abort()
            IStatusMessage(self.request).addStatusMessage(result, type='error')
            return self.index()

        # Get the thank you page.
        thankspage = self.context.thanksPage
        if not thankspage:
            thankspage = form.thanksPage
        thanks = form.get(thankspage)
        if thanks is None:
            thanks = form.unrestrictedTraverse('fg_result_view')
        return thanks()
Esempio n. 16
0
 def all_fields(self):
     context = aq_inner(self.context)
     fields = IAnnotations(context).get('collective.pfg.showrequest.fields')
     if fields is not None:
         objs = [
             (obj.id, obj) for obj in context._getFieldObjects() if (
                 not IField.providedBy(obj) or obj.isLabel()
             ) and obj.id in fields
         ]
         sorted_objs = []
         objs = dict(objs)
         for field in fields:
             sorted_objs.append(objs[field])
         res = []
         for obj in sorted_objs:
             value = obj.htmlValue(self.request)
             res.append({
                 'label': obj.fgField.widget.label,
                 'value': value,
             })
         return res
Esempio n. 17
0
    def __call__(self):
        box = self.context.get_box()
        secret = self.request.form.get('secret')
        email = self.request.form.get('email')
        data = box.pop(secret, token=email)

        if data is None:
            return self.index()

        alsoProvides(self.request, IConfirmedSubmission)
        form = self.context.get_form()
        fields = [fo for fo in form._getFieldObjects() if not IField.providedBy(fo)]

        # Put the data in the request.  Make it a dictionary,
        # otherwise the fg_result_view does not work, as an anonymous
        # user is not authorized to get items from the data, as it is
        # a PersistentMapping.
        self.request.form = dict(data)

        # Send mail that would be send when this would have been
        # a standard FormMailerAdapter.
        if self.context.send_standard_mail:
            self.context.send_form(fields, self.request)

        # Process the other adapters.  First argument is 'errors'.
        result = form.fgProcessActionAdapters({}, fields=fields, REQUEST=self.request)
        if result:
            # We have an error.  Abort any changes.
            transaction.abort()
            IStatusMessage(self.request).addStatusMessage(result, type='error')
            return self.index()

        # Get the thank you page.
        thankspage = self.context.thanksPage
        if not thankspage:
            thankspage = form.thanksPage
        thanks = form.get(thankspage)
        if thanks is None:
            thanks = form.unrestrictedTraverse('fg_result_view')
        return thanks()
    def hiddenFields(self, request):
        """ Returns sequence of dicts {'label':fieldlabel, 'value':input}
        """
        # get a list of all candidate fields
        myFields = []
        for obj in self.aq_parent._getFieldObjects():
            if not (IField.providedBy(obj) or obj.isLabel()):
                # if field list hasn't been specified explicitly, exclude server side fields
                if self.showAll and obj.getServerSide():
                    continue 
                myFields.append(obj)

        # Now, build the results list
        res = []
        for obj in myFields:
            value = obj.htmlValue(request)
            if self.includeEmpties or (value and (value != 'No Input')):
                res.append( {
                    'name' : obj.getId(),
                    'value' : value, 
                    } )
            
        return res
Esempio n. 19
0
    def displayInputs(self, request):
        """ Returns sequence of dicts {'label':fieldlabel, 'value':input}
        """
        # get a list of all candidate fields
        myFields = []
        for obj in self.aq_parent._getFieldObjects():
            if not (IField.providedBy(obj) or obj.isLabel()):
                # if field list hasn't been specified explicitly, exclude server side fields
                if self.showAll and obj.getServerSide():
                    continue
                myFields.append(obj)

        # Now, determine which fields we show
        if self.showAll:
            sFields = myFields
        else:
            sFields = []
            # acquire field list from parent
            res = []
            for id in self.showFields:
                # inefficient if we get many fields
                for f in myFields:
                    if f.getId() == id:
                        sFields.append(f)
                        break

        # Now, build the results list
        res = []
        for obj in sFields:
            value = obj.htmlValue(request)
            if self.includeEmpties or (value and (value != 'No Input')):
                res.append({
                    'label': obj.fgField.widget.label,
                    'value': value,
                })

        return res
Esempio n. 20
0
def finalize_registrant_creation(obj, event):
    """
    we are using a type created from uwosh FormSaveData2ContentEntry.
    So we need to get it by interface to cath the event, but here we need to
    check on portal_type, 'cause all the type created by uwosh stuff implements
    IFormSaveData2ContentEntry
    """
    # change the object state
    if obj.portal_type == 'registrant':
        site = getSite()
        portal_workflow = getToolByName(site, 'portal_workflow')
        portal_membership = getToolByName(site, 'portal_membership')
        current_state = portal_workflow.getInfoFor(obj, 'review_state')
        if current_state in ('new', ):
            signupsheet = obj.getForm()
            action = compute_next_action(obj, signupsheet)
            portal_workflow.doActionFor(obj, action)

        if portal_membership.isAnonymousUser():
            obj.setCreators(('(anonymous)', ))

        #Simulate mailer action
        #we want send also information about review state and we want mailer do
        #all the job
        form = obj.getForm()
        adapter = getattr(form.aq_explicit, 'user_notification_mailer', None)
        fields = [
            fo for fo in obj.getForm()._getFieldObjects()
            if not IField.providedBy(fo)
        ]
        obj.REQUEST['review_state'] = \
                signupsheetMessageFactory(unicode(portal_workflow.getInfoFor(obj,
                                                                             'review_state')))
        # If we are importing registrants from csv file, this flag allow to decide
        # to send or not notification mail
        if 'avoid_mail_notification' not in obj.REQUEST.form:
            adapter.onSuccess(fields, obj.REQUEST)
Esempio n. 21
0
def fgProcessActionAdapters(self, errors, fields=None, REQUEST=None):
    if fields is None:
        fields = [fo for fo in self._getFieldObjects()
                  if not IField.providedBy(fo)]

    if not errors:
        if self.getRawAfterValidationOverride():
            # evaluate the override.
            # In case we end up traversing to a template,
            # we need to make sure we don't clobber
            # the expression context.
            self.getAfterValidationOverride()
            self.cleanExpressionContext(request=self.REQUEST)

        # get a list of adapters with no duplicates, retaining order
        adapters = []
        for adapter in self.getRawActionAdapter():
            if adapter not in adapters:
                adapters.append(adapter)

        for adapter in adapters:
            actionAdapter = getattr(self.aq_explicit, adapter, None)
            if actionAdapter is None:
                logger.warn(
                    "Designated action adapter '%s' is missing; ignored. "
                    "Removing it from active list." %
                    adapter)
                self.toggleActionActive(adapter)
            else:
                # Now, see if we should execute it.
                # Check to see if execCondition exists and has contents
                if safe_hasattr(actionAdapter, 'execCondition') and \
                        len(actionAdapter.getRawExecCondition()):
                    # evaluate the execCondition.
                    # create a context for expression evaluation
                    context = getExprContext(self, actionAdapter)
                    doit = actionAdapter.getExecCondition(
                        expression_context=context)
                else:
                    # no reason not to go ahead
                    doit = True

                if doit:
                    result = actionAdapter.onSuccess(fields,
                                                     REQUEST=REQUEST)
                    if type(result) is type({}) and len(result):  # noqa
                        # return the dict, which hopefully uses
                        # field ids or FORM_ERROR_MARKER for keys
                        return result

        try:
            data = getData(self, fields, REQUEST)
        except:
            logger.info('could not collect stripe metadata')
            data = {}
        # see if there is a stripe field
        fields = [fo for fo in self._getFieldObjects()
                  if IStripeField.providedBy(fo)]

        for field in fields:
            name = field.fgField.getName()
            value = REQUEST.form[name]
            params = {
                'amount': value['amount'],
                'currency': field.getStripeCurrency(),
                'source': value['token'],
                'receipt_email': value['charge_data'].get('email')
            }
            mdata_fields = field.getStripeMetadata()
            if mdata_fields and type(mdata_fields) in (list, tuple, set):
                mcount = 0
                for key in mdata_fields:
                    if key in data:
                        value = data[key]
                        if not value:
                            continue
                        mcount += 1
                        if mcount >= 10:
                            break
                        # size limits here too
                        key = "metadata[%s]" % (
                            ''.join(c for c in key if c in valid_chars))
                        params[key] = value[:200]
            resp = requests.post(
                'https://api.stripe.com/v1/charges',
                auth=(field.getStripeSecretKey(), ''),
                data=params
            )
            try:
                data = resp.json()
                if 'error' in data:
                    errors[name] = 'Stripe API Errror: %s' % (
                        data['error']['message'])
            except:
                errors[name] = 'Error processing charge'
    return errors
Esempio n. 22
0
    def fgvalidate(self,
                   REQUEST=None,
                   errors=None,
                   data=None,
                   metadata=None,
                   skip_action_adapters=False):
        # Validates the field data from the request.

        if getattr(self, 'checkAuthenticator', True):
            # CSRF check.
            plone.protect.CheckAuthenticator(REQUEST)
            plone.protect.PostOnly(REQUEST)

        _marker = []
        if errors is None:
            errors = {}
        if errors:
            return errors

        # Get all the form fields. Exclude actual IField fields.
        fields = [fo for fo in self._getFieldObjects()
                  if not IField.providedBy(fo)]
        for obj in fields:
            field = obj.fgField

            if obj.isLabel() and obj.meta_type != 'FormRichLabelField':
                REQUEST.form[obj.__name__] = '1'

            if obj.getServerSide():
                # for server-side only fields, use the default value
                # even if something was in the request
                if obj.__name__ in REQUEST.form:
                    del REQUEST.form[obj.__name__]
                obj.fgPrimeDefaults(REQUEST)

            result = field.widget.process_form(self, field, REQUEST.form,
                                               empty_marker=_marker)

            if result is None or result is _marker:
                #XXX Make this smarter
                value = ''
            else:
                value = result[0]

            # workaround what I consider a Zope marshalling error:
            # the production of lists like ['one', ''] and ['']
            # for list fields. No need to worry about polymorphism here,
            # as this is a very particular case.
            if isinstance(value, type([])) and len(value) and \
              (type(value[-1]) in StringTypes) and (len(value[-1]) == 0):
                value.pop()

            # eliminate trailing white space in string types.
            if safe_hasattr(value, 'rstrip'):
                newvalue = value.rstrip()
                if newvalue != value:
                    value = newvalue
                    # since strings are immutable,
                    # we have to manually store it back to the request
                    if safe_hasattr(REQUEST, 'form'):
                        REQUEST.form[obj.getFieldFormName()] = value

            # Archetypes field validation
            res = field.validate(instance=self, value=value, errors=errors,
                                 REQUEST=REQUEST)

            if not res:
                # give the field itself an opportunity to validate.
                res = obj.specialValidator(value, field, REQUEST, errors)

            if res:
                errors[field.getName()] = \
                  validationMessages.cleanupMessage(res, self.REQUEST, self)
            elif shasattr(obj, 'getFgTValidator') and obj.getRawFgTValidator():
                # process the override validator TALES expression

                # create a context for expression evaluation
                context = getExprContext(self, obj)

                # put this field's input (from request)
                # into the context globals as 'value'
                context.setGlobal('value',
                                  REQUEST.form.get(obj.getFieldFormName(),
                                  None))

                # call the tales expression, passing our custom context
                cerr = obj.getFgTValidator(expression_context=context)
                if cerr:
                    errors[field.getName()] = cerr

        if not skip_action_adapters:
            return self.fgProcessActionAdapters(errors, fields, REQUEST)

        return errors
Esempio n. 23
0
File: form.py Progetto: dtgit/dtedu
    def fgvalidate(self, REQUEST=None, errors=None, data=None, metadata=None):
        """Validates the field data from the request.
        """

        _marker = []
        if errors is None:
            errors = {}
        if errors:
            return errors

        # Get all the form fields. Exclude actual IField fields.
        fields = [fo for fo in self._getFieldObjects() if not IField.isImplementedBy(fo)]

        for obj in fields:
            field = obj.fgField

            result = field.widget.process_form(self, field, REQUEST.form, empty_marker=_marker)

            if result is None or result is _marker:
                #XXX Make this smarter
                value = ''
            else:
                value = result[0]

            # workaround what I consider a Zope marshalling error: the production
            # of lists like ['one', ''] and [''] for list fields.
            # no need to worry about polymorphism here, as this is a very particular
            # case.        
            if isinstance(value, type([])) and len(value) and \
              (type(value[-1]) in StringTypes) and (len(value[-1]) == 0):
                value.pop()
                
            # eliminate trailing white space in string types.
            if safe_hasattr(value, 'rstrip'):
                newvalue = value.rstrip()
                if newvalue != value:
                    value = newvalue
                    # since strings are immutable, we have to manually store it back to the request
                    if safe_hasattr(REQUEST, 'form'):
                        REQUEST.form[obj.getFieldFormName()] = value                        

            # Archetypes field validation
            res = field.validate(instance=self, value=value, errors=errors, REQUEST=REQUEST)

            if not res:
                # give the field itself an opportunity to validate.
                res = obj.specialValidator(value, field, REQUEST, errors)

            if res:
                errors[field.getName()] = validationMessages.cleanupMessage(res, self.REQUEST, self)
            elif shasattr(obj, 'getFgTValidator') and obj.getRawFgTValidator():
                # process the override validator TALES expression

                # create a context for expression evaluation
                context = getExprContext(self, obj)
                
                # put this field's input (from request) into the context globals
                # as 'value'
                context.setGlobal('value', REQUEST.form.get(obj.getFieldFormName(), None))
                
                # call the tales expression, passing our custom context
                cerr = obj.getFgTValidator(expression_context=context)
                if cerr:
                    errors[field.getName()] = cerr

        if not errors:
            if self.getRawAfterValidationOverride():
                # evaluate the override.
                # In case we end up traversing to a template,
                # we need to make sure we don't clobber
                # the expression context.
                self.getAfterValidationOverride()
                self.cleanExpressionContext(request=self.REQUEST)

            adapters = self.getRawActionAdapter()
            for adapter in adapters:
                actionAdapter = getattr(self.aq_explicit, adapter, None)
                if actionAdapter is None:
                    logger.warn("Designated action adapter '%s' is missing; ignored." % adapter)
                else:
                    # Now, see if we should execute it.
                    # Check to see if execCondition exists and has contents
                    if safe_hasattr(actionAdapter, 'execCondition') and \
                      len(actionAdapter.getRawExecCondition()):
                        # evaluate the execCondition.
                        # create a context for expression evaluation
                        context = getExprContext(self, actionAdapter)
                        doit = actionAdapter.getExecCondition(expression_context=context)
                    else:
                        # no reason not to go ahead
                        doit = True

                    if doit:
                        result = actionAdapter.onSuccess(fields, REQUEST=REQUEST)
                        if type(result) is type({}) and len(result):
                            # return the dict, which hopefully uses
                            # field ids or FORM_ERROR_MARKER for keys
                            return result

        return errors
Esempio n. 24
0
    def fgvalidate(self,
                   REQUEST=None,
                   errors=None,
                   data=None,
                   metadata=None,
                   skip_action_adapters=False):
        # Validates the field data from the request.

        if getattr(self, 'checkAuthenticator', True):
            # CSRF check.
            plone.protect.CheckAuthenticator(REQUEST)
            plone.protect.PostOnly(REQUEST)

        _marker = []
        if errors is None:
            errors = {}
        if errors:
            return errors

        # Get all the form fields. Exclude actual IField fields.
        fields = [fo for fo in self._getFieldObjects()
                  if not IField.providedBy(fo)]
        for obj in fields:
            field = obj.fgField

            if obj.isLabel() and obj.meta_type != 'FormRichLabelField':
                REQUEST.form[obj.__name__] = '1'

            if obj.getServerSide():
                # for server-side only fields, use the default value
                # even if something was in the request
                if obj.__name__ in REQUEST.form:
                    del REQUEST.form[obj.__name__]
                obj.fgPrimeDefaults(REQUEST)

            result = field.widget.process_form(self, field, REQUEST.form,
                                               empty_marker=_marker)

            if result is None or result is _marker:
                #XXX Make this smarter
                value = ''
            else:
                value = result[0]

            # workaround what I consider a Zope marshalling error:
            # the production of lists like ['one', ''] and ['']
            # for list fields. No need to worry about polymorphism here,
            # as this is a very particular case.
            if isinstance(value, type([])) and len(value) and \
              (type(value[-1]) in StringTypes) and (len(value[-1]) == 0):
                value.pop()

            # eliminate trailing white space in string types.
            if safe_hasattr(value, 'rstrip'):
                newvalue = value.rstrip()
                if newvalue != value:
                    value = newvalue
                    # since strings are immutable,
                    # we have to manually store it back to the request
                    if safe_hasattr(REQUEST, 'form'):
                        REQUEST.form[obj.getFieldFormName()] = value

            # Archetypes field validation
            res = field.validate(instance=self, value=value, errors=errors,
                                 REQUEST=REQUEST)

            if not res:
                # give the field itself an opportunity to validate.
                res = obj.specialValidator(value, field, REQUEST, errors)

            if res:
                errors[field.getName()] = \
                  validationMessages.cleanupMessage(res, self.REQUEST, self)
            elif shasattr(obj, 'getFgTValidator') and obj.getRawFgTValidator():
                # process the override validator TALES expression

                # create a context for expression evaluation
                context = getExprContext(self, obj)

                # put this field's input (from request)
                # into the context globals as 'value'
                context.setGlobal('value',
                                  REQUEST.form.get(obj.getFieldFormName(),
                                  None))

                # call the tales expression, passing our custom context
                cerr = obj.getFgTValidator(expression_context=context)
                if cerr:
                    errors[field.getName()] = cerr

        if not skip_action_adapters:
            return self.fgProcessActionAdapters(errors, fields, REQUEST)

        return errors
Esempio n. 25
0
def fgProcessActionAdapters(self, errors, fields=None, REQUEST=None):
    if fields is None:
        fields = [
            fo for fo in self._getFieldObjects() if not IField.providedBy(fo)
        ]

    if not errors:
        if self.getRawAfterValidationOverride():
            # evaluate the override.
            # In case we end up traversing to a template,
            # we need to make sure we don't clobber
            # the expression context.
            self.getAfterValidationOverride()
            self.cleanExpressionContext(request=self.REQUEST)

        # get a list of adapters with no duplicates, retaining order
        adapters = []
        for adapter in self.getRawActionAdapter():
            if adapter not in adapters:
                adapters.append(adapter)

        for adapter in adapters:
            actionAdapter = getattr(self.aq_explicit, adapter, None)
            if actionAdapter is None:
                logger.warn(
                    "Designated action adapter '%s' is missing; ignored. "
                    "Removing it from active list." % adapter)
                self.toggleActionActive(adapter)
            else:
                # Now, see if we should execute it.
                # Check to see if execCondition exists and has contents
                if safe_hasattr(actionAdapter, 'execCondition') and \
                        len(actionAdapter.getRawExecCondition()):
                    # evaluate the execCondition.
                    # create a context for expression evaluation
                    context = getExprContext(self, actionAdapter)
                    doit = actionAdapter.getExecCondition(
                        expression_context=context)
                else:
                    # no reason not to go ahead
                    doit = True

                if doit:
                    result = actionAdapter.onSuccess(fields, REQUEST=REQUEST)
                    if type(result) is type({}) and len(result):  # noqa
                        # return the dict, which hopefully uses
                        # field ids or FORM_ERROR_MARKER for keys
                        return result

        try:
            data = getData(self, fields, REQUEST)
        except:
            logger.info('could not collect stripe metadata')
            data = {}
        # see if there is a stripe field
        fields = [
            fo for fo in self._getFieldObjects() if IStripeField.providedBy(fo)
        ]

        for field in fields:
            name = field.fgField.getName()
            value = REQUEST.form[name]
            params = {
                'amount': value['amount'],
                'currency': field.getStripeCurrency(),
                'source': value['token'],
                'receipt_email': value['charge_data'].get('email')
            }
            mdata_fields = field.getStripeMetadata()
            if mdata_fields and type(mdata_fields) in (list, tuple, set):
                mcount = 0
                for key in mdata_fields:
                    if key in data:
                        value = data[key]
                        if not value:
                            continue
                        mcount += 1
                        if mcount >= 10:
                            break
                        # size limits here too
                        key = "metadata[%s]" % (''.join(
                            c for c in key if c in valid_chars))
                        params[key] = value[:200]
            resp = requests.post('https://api.stripe.com/v1/charges',
                                 auth=(field.getStripeSecretKey(), ''),
                                 data=params)
            try:
                data = resp.json()
                if 'error' in data:
                    errors[name] = 'Stripe API Errror: %s' % (
                        data['error']['message'])
            except:
                errors[name] = 'Error processing charge'
    return errors