def sm_actions(self, project=None):
     getExprContext(self.context)
     ps = self.context.restrictedTraverse("@@plone_portal_state")
     base_url = ps.portal_url()
     if project is not None:
         base_url = project.absolute_url()
     for i in self._actions():
         current = self.request["URL"].split("/")[-1]
         yield {
             "title": i["title"],
             "id": i["id"],
             "url": "/".join((base_url, i["url"])),
             "description": i["description"],
             "class": " ".join((i["id"], current == i["id"] and "selected" or "")),
         }
    def render(self):
        """ Render the portlet if expression is evaluated succesfully.

        """

        #context = aq_inner(self.context)
        context = self.context
        expression_context = getExprContext(context)

        condition_value = True

        # Determine expression value in backwards compatible
        # manner
        expression = self.data._expression_object

        if expression:

            try:
                condition_value = expression(expression_context)

                if type(condition_value) in types.StringTypes:
                    if condition_value.strip() == u"":
                        # Emptry value evaluates to true
                        condition_value = True

            except Exception, e:
                # Log and output exception in user friendly
                # manner without interrupting the page rendering
                foobar, messages = Message.wrapCurrentException()
                outputTemplateErrors(messages, request=self.request, logger=logger, context=context)
                condition_value = False
Ejemplo n.º 3
0
def _getFieldObjects(self, objTypes=None, includeFSMarkers=False):
    """ return list of enclosed fields """

    # This function currently checks to see if
    # an object is a form field by looking to see
    # if it has an fgField attribute.

    # Make sure we look through fieldsets
    if objTypes is not None:
        objTypes = list(objTypes)[:]
        objTypes.append('FieldsetFolder')

    myObjs = []

    for obj in self.objectValues(objTypes):
        # use shasattr to make sure we're not aquiring
        # fgField by acquisition

        # TODO: If I stick with this scheme for enable overrides,
        # I'm probably going to want to find a way to cache the result
        # in the request. _getFieldObjects potentially gets called
        # several times in a request.

        # first, see if the field enable override is set
        if shasattr(obj, 'fgTEnabled') and obj.getRawFgTEnabled():
            # process the override enabled TALES expression
            # create a context for expression evaluation
            context = getExprContext(self, obj)
            # call the tales expression, passing our custom context
            enabled = obj.getFgTEnabled(expression_context=context)
        else:
            enabled = True

        if enabled:
            if shasattr(obj, 'fgField'):
                myObjs.append(obj)
            if shasattr(obj, 'fieldsetFields'):
                if queryAdapter(obj, interface=ISchemaExtender, name=config.PROJECT_NAME + FieldsetFolderExtender.__name__):
                    # Product is not installed --> nothing to patch
                    obj.setTitle(obj.Title())
                    obj.setDescription(obj.Description())
                myObjs += obj.fieldsetFields(objTypes, includeFSMarkers)

    for field in myObjs:

        if not queryAdapter(field, interface=ISchemaExtender, name=config.PROJECT_NAME + BaseFormFieldExtender.__name__):
            # Product is not installed --> nothing to patch
            continue
        
        field.setTitle(field.Title())
        field.setDescription(field.Description())
        if hasattr(field,'setFgDefault'):
            field.setFgDefault(field.getFgDefault())
        if isinstance(field.fgField, (StringVocabularyField, LinesVocabularyField,)):
            field.fgVocabulary = field.getFgVocabulary()
        if isinstance(field.fgField, LikertField):
            field.setLikertAnswers(field.getLikertAnswers())
            field.setLikertQuestions(field.getLikertQuestions())
    
    return myObjs
Ejemplo n.º 4
0
    def get_actions(self, category=''):
        """Returns the available and visible types actions
        in the given category
        """
        context = self.context
        types_tool = getToolByName(context, 'portal_types')
        ai_tool = getToolByName(context, 'portal_actionicons')
        actions = types_tool.listActions(object=context)
        plone_state = queryMultiAdapter((self.context, self.request),
                                        name='plone_portal_state')
        member = plone_state.member()

        for action in actions:
            wrong_permission = False
            for permission in action.permissions:
                if not member.has_permission(permission, self.context):
                    wrong_permission = True
                    continue

            if wrong_permission:
                continue

            if action.category == category:
                icon = ai_tool.queryActionIcon(action_id=action.id,
                                                category=category,
                                                context=context)
                econtext = getExprContext(context, context)
                action = action.getAction(ec=econtext)

                if action['available'] and action['visible']:
                    yield action, icon
 def __call__(self):
     orig_form = self.request.form.copy()
     for request in self.generator(self.context, self.request):
         
         # execute action adapters
         try:
             for actionAdapter in self.action_adapters:
                 # 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(self.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
         finally:
             self.request.form = orig_form
Ejemplo n.º 6
0
    def _metromap_transitions(self):
        """A data structure is stored as a TAL expression on a workflow which
        determines the sequence of workflow states/milestones used to render
        the metromap.

        We need to evaluate the expression and returns the data structure.

        It consists of a list of dicts each with the workflow state, the
        transition to the next milestone in the metromap, and the
        transition required to return to the milestone:
        [{
          'state': 'new',
          'next_transition': 'finalise',
          'reopen_transition': 'reset'
        }, {
          'state': 'complete',
          'next_transition': 'archive',
          'reopen_transition': 'finalise'
        }, {
          'state': 'archived'}
        ]
        """
        metromap_workflow = self._metromap_workflow
        if metromap_workflow is None:
            return []
        wfstep = metromap_workflow.variables["metromap_transitions"]
        tal_expr = wfstep.default_expr
        expr_context = getExprContext(self.context)
        metromap_transitions = tal_expr(expr_context)
        return metromap_transitions
 def render(self):
     """ Render the portlet if expression is evaluated succesfully.
     
     """
     
     #context = aq_inner(self.context)
     context = self.context
     expression_context = getExprContext(context)
     
     condition_value = True
     
     # Determine expression value in backwards compatible
     # manner    
     expression = self.data._expression_object
     
     if expression:
         
         try:        
             condition_value = expression(expression_context)
             
             if type(condition_value) in types.StringTypes:
                 if condition_value.strip() == u"":
                     # Emptry value evaluates to true
                     condition_value = True
             
         except Exception, e:
             # Log and output exception in user friendly
             # manner without interrupting the page rendering
             foobar, messages = Message.wrapCurrentException()
             outputTemplateErrors(messages, request=self.request, logger=logger, context=context)
             condition_value = False
Ejemplo n.º 8
0
 def available_widgets(self):
     types_tool = getToolByName(self, "portal_types")
     types = types_tool.listTypeInfo()
     available = []
     for type_info in types:
         dotted = getattr(type_info, 'klass', None)
         if not dotted:
             continue
         package, klass = dotted.rsplit('.', 1)
         try:
             __import__(package)
         except ImportError:
             continue
         klass = getattr(sys.modules[package], klass, None)
         if not ICompositionFragment.implementedBy(klass):
             continue
         expression = Expression(type_info.icon_expr)
         expression_context = getExprContext(self)
         icon = expression(expression_context)
         available.append({
             'portal_type': type_info.id,
             'icon': icon,
             'title': type_info.title,
             'description': type_info.description
         })
     return available
Ejemplo n.º 9
0
    def get_actions(self, category=''):
        """Returns the available and visible types actions
        in the given category
        """
        context = self.context
        types_tool = getToolByName(context, 'portal_types')
        actions = types_tool.listActions(object=context)
        plone_state = queryMultiAdapter((self.context, self.request),
                                        name='plone_portal_state')
        member = plone_state.member()

        for action in actions:
            wrong_permission = False
            for permission in action.permissions:
                if not member.has_permission(permission, self.context):
                    wrong_permission = True
                    continue

            if wrong_permission:
                continue

            if action.category == category:
                icon = None
                econtext = getExprContext(context, context)
                action = action.getAction(ec=econtext)

                if action['available'] and action['visible']:
                    yield action, icon
Ejemplo n.º 10
0
    def fgPrimeDefaults(self, request, contextObject=None):
        """ primes request with default """
        value = None

        # try and look up the current state
        formFolder = self.formFolderObject()
        if formFolder.getAllowEditPrevious():
            value = formFolder.getExistingValue(self.aq_base)

        # the field macros will try to get the field value
        # via Field.getEditAccessor. Unfortunately, it looks for it
        # as an attribute of the object, not the field.
        # so, communicate via the request, but don't overwrite
        # what's already there.
        if value is None:
            if safe_hasattr(self, 'getFgTDefault') and self.getRawFgTDefault():
                if contextObject:
                    # see note in fgvalidate
                    value = self.getFgTDefault(expression_context=getExprContext(self, contextObject))
                else:
                    value = self.getFgTDefault()

        if (value is None) and safe_hasattr(self, 'getFgDefault'):
            value = self.getFgDefault()
        if value:
            request.form.setdefault(self.fgField.__name__, value)
Ejemplo n.º 11
0
 def __call__(self, root, extras={}):
     context = extras.get('context')
     expr_context = getExprContext(context, context)
     try:
         return bool(self.expression(expr_context))
     except:
         return False
Ejemplo n.º 12
0
    def _metromap_transitions(self):
        """A data structure is stored as a TAL expression on a workflow which
        determines the sequence of workflow states/milestones used to render
        the metromap.

        We need to evaluate the expression and returns the data structure.

        It consists of a list of dicts each with the workflow state, the
        transition to the next milestone in the metromap, and the
        transition required to return to the milestone:
        [{
          'state': 'new',
          'next_transition': 'finalise',
          'reopen_transition': 'reset'
        }, {
          'state': 'complete',
          'next_transition': 'archive',
          'reopen_transition': 'finalise'
        }, {
          'state': 'archived'}
        ]
        """
        metromap_workflow = self._metromap_workflow
        if metromap_workflow is None:
            return []
        wfstep = metromap_workflow.variables["metromap_transitions"]
        tal_expr = wfstep.default_expr
        expr_context = getExprContext(self.context)
        metromap_transitions = tal_expr(expr_context)
        return metromap_transitions
Ejemplo n.º 13
0
    def _evaluate_expression(expression):
        portal = api.portal.get()
        expression = Expression(expression)

        expression_context = getExprContext(context=portal)

        return expression(expression_context)
Ejemplo n.º 14
0
    def map_defaults(self):
        settings = getMultiAdapter(
            (self.context, self.request), name='geosettings-view'
        )
        lon, lat = settings.map_center
        pstate = getMultiAdapter(
            (self.context, self.request), name='plone_portal_state'
        )
        portal_url = pstate.portal_url()

        # Image path for changing OpenLayers default images.
        # TODO: check if settings are overriden for this context
        try:
            expr = Expression(str(settings.imgpath))
            imgpath = expr(getExprContext(self.context))
        except:
            imgpath = ''

        return {
            'longitude': lon,
            'latitude': lat,
            'zoom': settings.zoom,
            'imgpath': imgpath,
            'geocoderurl': "%s/geocoderview" % portal_url
        }
Ejemplo n.º 15
0
def get_marker_image(context, marker_img):
    try:
        marker_img = Expression(str(marker_img))(getExprContext(context))
    except CompilerError:
        logger.info('Could not parse expression {}'.format(marker_img))
        marker_img = '{}/{}'.format(context.portal_url(), marker_img)
    return marker_img
Ejemplo n.º 16
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
Ejemplo n.º 17
0
def execExpression(self, expression):
  """
    Allow exec <Products.CMFCore.Expression.Expression object ..> instances from 
    within  restricted environment.
    XXX: consider its security impact
  """
  econtext = getExprContext(self)
  return expression(econtext)
Ejemplo n.º 18
0
def get_formatted_data_from_json(tal_expression, item, item_data):
    if not tal_expression:
        return None
    expression = Expression(tal_expression)
    expression_context = getExprContext(item)
    expression_context.vars["json"] = item_data
    expression_result = expression(expression_context)
    return expression_result
Ejemplo n.º 19
0
def execExpression(self, expression):
    """
    Allow exec <Products.CMFCore.Expression.Expression object ..> instances from 
    within  restricted environment.
    XXX: consider its security impact
  """
    econtext = getExprContext(self)
    return expression(econtext)
Ejemplo n.º 20
0
    def _set_item(self,item,current):
        """ """
        context=self.context
        check_perm=context.getAdapter('checkperm')
        translate=context.getAdapter('translate')

        if IAction.providedBy(item):
            for permission in item.permissions:
                if not check_perm(permission):
                    return

        dict_={}

        if IAction.providedBy(item):
            show=True
            if item.available_expr and not Expression(item.available_expr)(getExprContext(context,context)):
                show=False
            for permission in item.permissions:
                if not check_perm(permission):
                    show=False
                    return
            if not show:
                return

        if IAction.providedBy(item):
            dict_['title']=translate(msgid=getattr(item,'msgid',item.title),domain=item.i18n_domain,default=item.title)
        else:
            domain=item.getProperty('domain','plone')
            msgid=item.getProperty('msgid',item.title)
            dict_['title']=translate(msgid=msgid,domain=domain,default=item.title)

        if IActionCategory.providedBy(item):
            dict_['children']=[]
            dict_['interface']='IActionCategory'

        if IAction.providedBy(item):
            dict_['interface']='IAction'
            dict_['target']=item.getProperty('link_target','_self')
            dict_['class']=item.getProperty('class_','')
            dict_['url']=Expression(item.url_expr)(getExprContext(context,context))
            dict_['onclick']=item.getProperty('onclick','')

        current.append(dict_)

        return dict_
Ejemplo n.º 21
0
 def isEditable(self, context=None):
     if self.getRawEditMode():
         if context:
             value = self.getEditMode(
                 expression_context=getExprContext(self, context))
         else:
             value = self.getEditMode()
         return value
     return False
Ejemplo n.º 22
0
 def __call__(self, node, extras={}):
     context = extras.get('context')
     expr_context = getExprContext(context, context)
     try:
         result = fromstring(self.expression(expr_context))
         if type(result) == HtmlElement:
             return [result]
         return result
     except:
         return []
Ejemplo n.º 23
0
 def types(self):
     """List all type icons
     Type actions are always visible"""
     ttool = getUtility(ITypesTool)
     types = ttool.listTypeInfo()
     econtext = getExprContext(self.context)
     icons = [self.icon_style %  (t.id,
                               t.getIconExprObject()(econtext)) \
             for t in types]
     return "\n\n".join(icons)
Ejemplo n.º 24
0
 def sm_actions(self, project=None):
     getExprContext(self.context)
     ps = self.context.restrictedTraverse('@@plone_portal_state')
     base_url = ps.portal_url()
     if project is not None:
         base_url = project.absolute_url()
     for i in self._actions():
         current = self.request['URL'].split('/')[-1]
         yield {
             'title':
             i['title'],
             'id':
             i['id'],
             'url':
             '/'.join((base_url, i['url'])),
             'description':
             i['description'],
             'class':
             ' '.join((i['id'], current == i['id'] and 'selected' or ''))
         }
Ejemplo n.º 25
0
 def value(item):
     expression_context = getExprContext(self.context, self.context)
     expression_context.setLocal('item', item)
     try:
         val = expression(expression_context)
     except (AttributeError, IndexError, KeyError, NameError, TypeError, ValueError, ZeroDivisionError):
         portal_membership = getToolByName(self, 'portal_membership')
         if not portal_membership.checkPermission('Manage portal', self.context):
             return None
         val = 'The custom field expression has an error: %s.' % expression.text
     return {'title': field.name, 'css_class': css_class, 'value': val, 'is_custom': True}
Ejemplo n.º 26
0
 def getIconURL(self):
     """ Get the absolute URL of the icon for the object.
     """
     ti = self.getTypeInfo()
     if ti is None:
         utool = getToolByName(self, 'portal_url')
         return '%s/misc_/OFSP/dtmldoc.gif' % utool()
     icon_expr_object = ti.getIconExprObject()
     if icon_expr_object is None:
         return ''
     ec = getExprContext(self)
     return icon_expr_object(ec)
Ejemplo n.º 27
0
 def getIconURL(self):
     """ Get the absolute URL of the icon for the object.
     """
     ti = self.getTypeInfo()
     if ti is None:
         utool = getToolByName(self, 'portal_url')
         return '%s/misc_/OFSP/dtmldoc.gif' % utool()
     icon_expr_object = ti.getIconExprObject()
     if icon_expr_object is None:
         return ''
     ec = getExprContext(self)
     return icon_expr_object(ec)
Ejemplo n.º 28
0
    def fgProcessActionAdapters(self, errors, fields=None, REQUEST=None):
        if fields is None:
            fields = [
                fo for fo in self._getFieldObjects()
                if not implementedOrProvidedBy(IField, 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
Ejemplo n.º 29
0
def get_expression(context, expression_string, **kwargs):
    """ Get TALES expression

    :param context: [required] TALES expression context
    :param string expression_string: [required] TALES expression string
    :param dict kwargs: additional arguments for expression
    :returns: result of TALES expression
    """
    expression_context = getExprContext(context, context)
    for key in kwargs:
        expression_context.setGlobal(key, kwargs[key])
    expression = Expression(expression_string)
    return expression(expression_context)
Ejemplo n.º 30
0
    def get_management_dict(self):
        """Return dictionary where 'key' group manage 'value' groups.

        '*' meaning all users. Leave empty to allow creation of user accounts
        without any management. eg python:{'Administrators': ['*']}. This TALES
        expression is allowing all the users managed by 'Administrators' group.
        """
        expression_context = getExprContext(self, self.aq_parent)
        manage_group = self.getManage_group_template(
            expression_context=expression_context)
        # make sure manage_group is dictionary
        if not isinstance(manage_group, dict):
            return {}
        return manage_group
 def evaluate_exp(self, ctx, expression):
     expression_context = getExprContext(self, ctx)
     # works but It's not perfectly clear how
     # http://collective-docs.readthedocs.org/en/latest/functionality/expressions.html
     value = expression(expression_context)
     if hasattr(value, 'strip') and value.strip() == "":
         # Usually empty expression field means that
         # expression should be True
         value = True
     if value:
         # Expression succeeded
         return True
     else:
         return False
Ejemplo n.º 32
0
 def getIcon(self, absolute=False):
     """
         Returns the icon for this content object.
     """
     if self.content_icon:
         return self.content_icon
     icon_expr = getattr(self, 'icon_expr_object', None)
     if icon_expr:
         ec = getExprContext(self)
         icon = icon_expr(ec)
         if absolute:
             return icon
         if isinstance(icon, basestring):
             return icon.split('/')[-1]
     return ''
Ejemplo n.º 33
0
 def getIcon(self, absolute=False):
     """
         Returns the icon for this content object.
     """
     if self.content_icon:
         return self.content_icon
     icon_expr = getattr(self, 'icon_expr_object', None)
     if icon_expr:
         ec = getExprContext(self)
         icon = icon_expr(ec)
         if absolute:
             return icon
         if isinstance(icon, basestring):
             return icon.split('/')[-1]
     return ''
Ejemplo n.º 34
0
    def __call__(self):
        self.request.set('disable_border', True)
        context = aq_inner(self.context)
        sdm = getToolByName(context, 'session_data_manager')
        session = sdm.getSessionData(create="False")
        items = session.get('collective.pfg.payment', {})
        self.request.form = items
        parent = aq_parent(context)
        try:
            # PloneFormGen-1.6.0
            parent.fgProcessActionAdapters(None,
                                           fields=None,
                                           REQUEST=self.request)
        except AttributeError:
            # PloneFormGen-1.2.7
            adapters = parent.getRawActionAdapter()
            for adapter in adapters:
                actionAdapter = getattr(parent.aq_explicit, adapter, None)
                if actionAdapter is None:
                    pass
                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(parent, actionAdapter)
                        doit = actionAdapter.getExecCondition(
                            expression_context=context)
                    else:
                        # no reason not to go ahead
                        doit = True

                    if doit:
                        names = items.keys()
                        fields = [parent[name] for name in names]
                        result = actionAdapter.onSuccess(fields,
                                                         REQUEST=self.request)
                        if isinstance(result, dict) and len(result):
                            # return the dict, which hopefully uses
                            # field ids or FORM_ERROR_MARKER for keys
                            return result

        self.items = context.displayInputs(self.request)
        if session.get('collective.pfg.payment.number'):
            del session['collective.pfg.payment.number']
        return self.template()
Ejemplo n.º 35
0
    def _getFieldObjects(self,
                         objTypes=None,
                         includeFSMarkers=False,
                         checkEnabled=True):
        """ return list of enclosed fields """

        # This function currently checks to see if
        # an object is a form field by looking to see
        # if it has an fgField attribute.

        # Make sure we look through fieldsets
        if objTypes is not None:
            objTypes = list(objTypes)[:]
            objTypes.extend(('FieldsetFolder', 'FieldsetStart', 'FieldsetEnd'))

        myObjs = []

        for obj in self.objectValues(objTypes):
            # use shasattr to make sure we're not aquiring
            # fgField by acquisition

            # TODO: If I stick with this scheme for enable overrides,
            # I'm probably going to want to find a way to cache the result
            # in the request. _getFieldObjects potentially gets called
            # several times in a request.

            # first, see if the field enable override is set
            if checkEnabled and shasattr(
                    obj, 'fgTEnabled') and obj.getRawFgTEnabled():
                # process the override enabled TALES expression
                # create a context for expression evaluation
                context = getExprContext(self, obj)
                # call the tales expression, passing our custom context
                enabled = obj.getFgTEnabled(expression_context=context)
            else:
                enabled = True

            if enabled:
                if shasattr(obj, 'fgField'):
                    myObjs.append(obj)
                elif shasattr(obj, 'fieldsetFields'):
                    myObjs += obj.fieldsetFields(objTypes, includeFSMarkers)
                elif obj.portal_type == 'FieldsetStart':
                    myObjs.append(obj.fsStartField)
                elif obj.portal_type == 'FieldsetEnd':
                    myObjs.append(obj.fsEndField)

        return myObjs
Ejemplo n.º 36
0
def get_expression(context, expression_string, **kwargs):
    """ Get TALES expression

    :param context: [required] TALES expression context
    :param string expression_string: [required] TALES expression string
    :param dict kwargs: additional arguments for expression
    :returns: result of TALES expression
    """
    if isinstance(expression_string, unicode):
        expression_string = expression_string.encode('utf-8')

    expression_context = getExprContext(context, context)
    for key in kwargs:
        expression_context.setGlobal(key, kwargs[key])
    expression = Expression(expression_string)
    return expression(expression_context)
Ejemplo n.º 37
0
 def getIconURL(self):
     """ Get the absolute URL of the icon for the object.
     """
     ti = self.getTypeInfo()
     if ti is None:
         try:
             utool = getUtility(IURLTool)
         except ComponentLookupError:
             # BBB: fallback for CMF 2.2 instances
             utool = aq_get(self, 'portal_url')
         return '%s/misc_/OFSP/dtmldoc.gif' % utool()
     icon_expr_object = ti.getIconExprObject()
     if icon_expr_object is None:
         return ''
     ec = getExprContext(self)
     return icon_expr_object(ec)
Ejemplo n.º 38
0
 def getIconURL(self):
     """ Get the absolute URL of the icon for the object.
     """
     ti = self.getTypeInfo()
     if ti is None:
         try:
             utool = getUtility(IURLTool)
         except ComponentLookupError:
             # BBB: fallback for CMF 2.2 instances
             utool = aq_get(self, 'portal_url')
         return '%s/misc_/OFSP/dtmldoc.gif' % utool()
     icon_expr_object = ti.getIconExprObject()
     if icon_expr_object is None:
         return ''
     ec = getExprContext(self)
     return icon_expr_object(ec)
    def get_menu_tabs(self):
        context = self.context.aq_inner
        context_path = "/".join(context.getPhysicalPath())
        settings = self.menu_settings
        if not settings:
            return []
        results = []

        for i, tab_settings in enumerate(settings):
            # evaluate condition
            condition = tab_settings.condition or ''
            expression = Expression(condition)
            expression_context = getExprContext(self.context, self.context)
            value = expression(expression_context)

            if isinstance(value, basestring) and value.strip() == "":
                value = True

            if not value:
                continue

            tab_title = getattr(tab_settings, "tab_title", '')
            if not tab_title:
                continue

            tab_dict = {'index': i}
            # this text is used inside a link, so i can't use portal_transorms
            # because it wraps all inside a <p> tag.
            # I wrap every row inside a span, so they can be easily styled
            rows = ["<span>%s</span>" % x for x in tab_title.split("\r\n")]
            # tab_dict['title'] = "<br/>".join(rows)
            tab_dict['title'] = "".join(rows)

            navigation_folder = self.get_navigation_folder(tab_settings)
            #need to do something better
            if navigation_folder == '__skip_this_folder__':
                continue

            if navigation_folder:
                tab_dict['url'] = navigation_folder.absolute_url()
                tab_dict['selected'] = context_path.startswith(
                    "/".join(navigation_folder.getPhysicalPath()))
            if tab_settings.simple_link:
                tab_dict['url'] = tab_settings.simple_link
                tab_dict['clickandgo'] = True
            results.append(tab_dict)
        return results
Ejemplo n.º 40
0
 def update_data_approval_group(self, data_user_group):
     # Split the manage_group_template into two:
     # manage_group and approval_group
     # manage_group_template can't use data argument any more
     # because it will use when form data is not available
     expression_context = getExprContext(self, self.aq_parent)
     manage_group = self.getManage_group_template(
         expression_context=expression_context)
     is_manage_group_dict = isinstance(manage_group, dict)
     data_approval_group = []
     if manage_group and is_manage_group_dict:
         for manager, user_list in manage_group.iteritems():
             if '*' in user_list:
                 data_approval_group.append(manager)
             elif data_user_group in user_list:
                 data_approval_group.append(manager)
     return data_approval_group
Ejemplo n.º 41
0
    def _getSchemas(self):
        schemas = []
        for schema_name, settings, condition, schema in self._getSchemaInfo():
            types = settings.types
            if 'File' in types:
                types = types | set(['Blob'])
            if self.context.portal_type not in types:
                continue

            if condition is not None and getattr(self.context, 'REQUEST', None) is getRequest():
                econtext = getExprContext(self.context, self.context)
                if not Expression(settings.condition)(econtext):
                    continue

            schemas.append((schema_name, schema))

        return schemas
    def update(self):
                                        
        try:
            topMenu = aq_acquire(self.context, 'top-menu')
        except AttributeError:
            topMenu = 'topnavigation'
            
        self.topnavigation = self.context_state.actions().get(topMenu, None)

        # URL that contains the section
        self.container_url = None

        if self.topnavigation:
            matches = []
    
            for t in self.topnavigation:
                portal_url = self.context.portal_url()
                context_url = self.context.absolute_url()
                menu_url = t.get('url')
                urls = [menu_url]
                
                # Handle additional URLs configured in portal_actions
                if t.get('additional_urls'):
                    econtext = getExprContext(self.context)
                    for u in t.get('additional_urls'):
                        try:
                            url_expr = Expression(u)
                            urls.append(url_expr.__call__(econtext))
                        except:
                            pass
                        
                for t_url in urls:
                    # Remove trailing / to normalize
                    if t_url.endswith("/"):
                        t_url = t_url[0:-1]
                    if portal_url.endswith("/"):
                        portal_url = portal_url[0:-1]
                    if context_url.endswith("/"):
                        context_url = context_url[0:-1]
                        
                    if portal_url != t_url and context_url.startswith(t_url):
                        matches.append(menu_url) # Remove trailing slash

            if matches:
                self.container_url = sorted(matches, key=lambda x:len(x), reverse=True)[0]
Ejemplo n.º 43
0
    def Title(self):
        """
        generate custom title from the selected
        form field or the given TALES expression override
        """
        adapter = self.getFormAdapter()
        if not adapter:
            return self.getId()
        # If there's a TALES expression:
        if adapter.getRawDynamicTitle():
            # TALES expr evaluation may require permissions an anonymous user
            # does not have. So we set up a new security manager and pose as
            # an Owner.
            old_security_manager = getSecurityManager()
            user = self.getWrappedOwner()
            newSecurityManager(None, user)

            # Try evaluating it
            exprcontext = getExprContext(self, self)
            try:
                value = adapter.getDynamicTitle(
                    expression_context=exprcontext)
                setSecurityManager(old_security_manager)
                return value
            except Exception:
                # make sure original security manager is reinstated.
                setSecurityManager(old_security_manager)
                raise

        # Ok. No override, resort to using a selected field
        field = adapter.getTitleField()
        schema = self.Schema()
        if field in schema:
            value = schema.get(field).get(self)
            try:
                if not isinstance(value, basestring):
                    # not of string type so convert it
                    # This may not always work but might prevent some errors.
                    value = str(value)
            except:
                pass

            return value
        else:
            return self.getId()
Ejemplo n.º 44
0
    def _getFieldObjects(self, objTypes=None, includeFSMarkers=False, checkEnabled=True):
        """ return list of enclosed fields """

        # This function currently checks to see if
        # an object is a form field by looking to see
        # if it has an fgField attribute.

        # Make sure we look through fieldsets
        if objTypes is not None:
            objTypes = list(objTypes)[:]
            objTypes.extend(('FieldsetFolder', 'FieldsetStart', 'FieldsetEnd'))

        myObjs = []

        for obj in self.objectValues(objTypes):
            # use shasattr to make sure we're not aquiring
            # fgField by acquisition

            # TODO: If I stick with this scheme for enable overrides,
            # I'm probably going to want to find a way to cache the result
            # in the request. _getFieldObjects potentially gets called
            # several times in a request.

            # first, see if the field enable override is set
            if checkEnabled and shasattr(obj, 'fgTEnabled') and obj.getRawFgTEnabled():
                # process the override enabled TALES expression
                # create a context for expression evaluation
                context = getExprContext(self, obj)
                # call the tales expression, passing our custom context
                enabled = obj.getFgTEnabled(expression_context=context)
            else:
                enabled = True

            if enabled:
                if shasattr(obj, 'fgField'):
                    myObjs.append(obj)
                elif shasattr(obj, 'fieldsetFields'):
                    myObjs += obj.fieldsetFields(objTypes, includeFSMarkers)
                elif obj.portal_type == 'FieldsetStart':
                    myObjs.append(obj.fsStartField)
                elif obj.portal_type == 'FieldsetEnd':
                    myObjs.append(obj.fsEndField)

        return myObjs
Ejemplo n.º 45
0
Archivo: form.py Proyecto: vwc/fv
    def fgProcessActionAdapters(self, errors, fields=None, REQUEST=None):
        if fields is None:
            fields = [fo for fo in self._getFieldObjects()
                      if not implementedOrProvidedBy(IField, 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)

            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
    def fgPrimeDefaults(self, request, contextObject=None):
        """ primes request with default """

        # the field macros will try to get the field value
        # via Field.getEditAccessor. Unfortunately, it looks for it
        # as an attribute of the object, not the field.
        # so, communicate via the request, but don't overwrite
        # what's already there.

        if safe_hasattr(self, 'getFgTDefault') and self.getRawFgTDefault():
            if contextObject:
                # see note in fgvalidate
                value = self.getFgTDefault(expression_context=getExprContext(self, contextObject))
            else:
                value = self.getFgTDefault()
        else:
            value = None

        if (value is None) and safe_hasattr(self, 'getFgDefault'):
            value = self.getFgDefault()
        if value:
            request.form.setdefault(self.fgField.__name__, value)
Ejemplo n.º 47
0
    def __call__(self):
        super(OpenGraphBase, self).__call__()
        self.properties.append(('og:title', self.title))
        self.properties.append(('og:description', self.description))

        if self.image:
            large = self.getScale(width=1000, height=1000)
            if large:
                self.properties.append(('og:image', large.url))
                self.properties.append(
                    ('og:image:type', self.image.contentType))
                self.properties.append(('og:image:width', large.width))
                self.properties.append(('og:image:height', large.height))
        elif self.seoSettings.openGraphFallbackImage:
            expression = Expression(
                str(self.seoSettings.openGraphFallbackImage))
            expression_context = getExprContext(self.context)
            self.properties.append(
                ('og:image', expression(expression_context)))

        context_state = getMultiAdapter((self.context, self.request),
                                        name=u'plone_context_state')
        canonical_url = context_state.canonical_object_url()
        self.properties.append(('og:url', canonical_url))

        portal_properties = getToolByName(self.context, 'portal_properties')
        loc = portal_properties.site_properties.getProperty('default_language')
        if '-' in loc:
            loc = loc.split('-')[0] + '_' + loc.split('-')[1].upper()
        if '_' not in loc:
            # make sure its nl_NL or en_US
            loc = loc.lower() + '_' + loc.upper()
        self.properties.append(('og:locale', loc))

        self.portal_state = getMultiAdapter((self.context, self.request),
                                            name=u'plone_portal_state')
        portal_title = escape(
            safe_unicode(self.portal_state.navigation_root_title()))
        self.properties.append(('og:site_name', portal_title))
    def map_defaults(self):
        settings = getMultiAdapter((self.context, self.request),
                                   name='geosettings-view')
        lon, lat = settings.map_center
        pstate = getMultiAdapter((self.context, self.request),
                                 name='plone_portal_state')
        portal_url = pstate.portal_url()

        # Image path for changing OpenLayers default images.
        # TODO: check if settings are overriden for this context
        try:
            expr = Expression(str(settings.imgpath))
            imgpath = expr(getExprContext(self.context))
        except:
            imgpath = ''

        return {
            'longitude': lon,
            'latitude': lat,
            'zoom': settings.zoom,
            'imgpath': imgpath,
            'geocoderurl': "%s/geocoderview" % portal_url
        }
Ejemplo n.º 49
0
    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

        field = self.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 [''].
        # 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[self.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 = self.specialValidator(value, field, REQUEST, errors)

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

            # create a context for expression evaluation.
            # Note that we're explicitly passing the form object to getExprContext;
            # this makes sure we don't cache the wrong context.
            context = getExprContext(self, self.aq_parent)

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

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

        return errors
Ejemplo n.º 50
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 implementedOrProvidedBy(IField, 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
Ejemplo n.º 51
0
def get_marker_image(context, marker_img):
    try:
        marker_img = Expression(str(marker_img))(getExprContext(context))
    except CompilerError:
        marker_img = "{}/{}".format(context.absolute_url(), marker_img)
    return marker_img
Ejemplo n.º 52
0
 def evaluate(self, context, expression):
     ec = getExprContext(context, context)
     expr = Expression(expression)
     return expr(ec)
Ejemplo n.º 53
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
Ejemplo n.º 54
0
 def getValueFor(self, field):
     value = getattr(self.seoSettings, field)
     if value:
         expression = Expression(str(value))
         expression_context = getExprContext(self.context)
         return expression(expression_context)
Ejemplo n.º 55
0
 def _getExprContext(self, object):
     return getExprContext(self, object)
Ejemplo n.º 56
0
    def test_07_DateTimeFieldWithModuleCreation(self):
        '''test DateTime format'''

        self.portal.ERP5Site_createModuleScribus(
            option_html=1,
            desired_width=800,
            desired_height=600,
            module_portal_type="Authorisation Module",
            portal_skins_folder="erp5_authorisation",
            object_portal_type="Authorisation",
            object_title="Authorisation",
            module_id="authorisation_module",
            module_title="Authorisation Module Title",
            import_pdf_file=self.makeFileUpload('Authorisation.pdf'),
            import_scribus_file=self.makeFileUpload('Authorisation.sla'),
        )
        portal = self.getPortal()
        portal_types = self.portal.portal_types
        self.assertNotEqual(self.portal._getOb('authorisation_module', None),
                            None)
        self.assertNotEqual(
            self.portal.portal_skins._getOb("erp5_authorisation", None), None)
        self.assertEqual("Authorisation Module Title",
                         self.portal.authorisation_module.getTitle())
        module_portal_type = portal_types.getTypeInfo("Authorisation Module")
        self.assertNotEqual(module_portal_type, None)
        self.assertNotEqual(portal_types.getTypeInfo("Authorisation"), None)
        # Create an Authorisation
        # add property sheet Task in portal type Authorisation
        self.portal.portal_types.Authorisation._setTypePropertySheet('Task')
        authorisation_module = self.portal.authorisation_module
        start_date = DateTime('2000/01/01')
        stop_date = DateTime('2001/01/01 12:00 GMT')
        authorisation = authorisation_module.newContent(\
              portal_type='Authorisation',
              title = 'Mum Dad',
              start_date = start_date,
              stop_date = stop_date
            )

        form = self.portal.portal_skins.erp5_authorisation.Authorisation_view
        # test property input_order on all DateTimeField
        input_order_other_date = form.my_other_date.get_value('input_order')
        input_order_start_date = form.my_start_date.get_value('input_order')
        input_order_stop_date = form.my_stop_date.get_value('input_order')
        self.assertEqual(input_order_other_date, 'ymd')
        self.assertEqual(input_order_start_date, 'dmy')
        self.assertEqual(input_order_stop_date, 'ymd')
        # test result of expression TALES with DateTimeField
        form = self.portal.portal_skins.erp5_authorisation
        pdf = form.Authorisation_viewAuthorisationAsPdf
        cell_name_other_date = pdf.getCellNames()[0]
        cell_name_start_date = pdf.getCellNames()[1]
        cell_name_stop_date = pdf.getCellNames()[2]
        tales_expr_other_date = pdf.getCellTALES(cell_name_other_date)
        tales_expr_start_date = pdf.getCellTALES(cell_name_start_date)
        tales_expr_stop_date = pdf.getCellTALES(cell_name_stop_date)
        from Products.CMFCore.Expression import Expression
        from Products.CMFCore.Expression import getExprContext
        expr_other_date = Expression(tales_expr_other_date)
        expr_start_date = Expression(tales_expr_start_date)
        expr_stop_date = Expression(tales_expr_stop_date)
        result_other_date = expr_other_date(
            getExprContext(authorisation, authorisation))
        result_start_date = expr_start_date(
            getExprContext(authorisation, authorisation))
        result_stop_date = expr_stop_date(
            getExprContext(authorisation, authorisation))
        self.assertEqual(result_other_date, '')
        self.assertEqual(result_start_date, start_date.strftime('%d/%m/%Y'))
        self.assertEqual(result_stop_date,
                         stop_date.strftime('%Y/%m/%d %H:%M'))
Ejemplo n.º 57
0
    def run(self, resource, *args, **kwds):
        """change the rdf resource

        We implement this type of output:
          <eea:Article rdf:about="http://example.com/articleA">
            <foaf:depiction>
              <schema:Image rdf:about="http://example.com/article-icon.png">
                <rdfs:label>type_icon</rdfs:label>
              </schema:Image>
            </foaf:depiction>
            <foaf:depiction>
              <schema:Image rdf:about="http://example.com/articleA/image">
                <schema:thumbnail
                  rdf:resource="http://example.com/articleA/image_large"/>
                <schema:thumbnail
                  rdf:resource="http://example.com/articleA/image_preview"/>
                <rdfs:label>depiction</rdfs:label>
                <eea:fileInfo
                  rdf:resource="http://example.com/articleA/image#fileInfo"/>
                <schema:contentSize>1234</schema:contentSize>
              </schema:Image>
            </foaf:depiction>
            <article:image rdf:resource="http://example.com/articleA/image"/>
          </eea:Article>
          <schema:Image rdf:about="http://example.com/articleA/image_preview">
            <schema:width>300px</schema:width>
            <schema:height>100px</schema:height>
          </schema:Image>
          <dcat:Distribution
            rdf:about="http://example.com/articleA/image#fileInfo">
            <dcat:downloadURL
              rdf:resource="http://example.com/articleA/at_download/image"/>
            <dcat:sizeInBytes>1234</dcat:sizeInBytes>
          </dcat:Distribution>
          <schema:Image rdf:about="http://example.com/articleA/image_large">
            <schema:width>400px</schema:width>
            <schema:height>200px</schema:height>
          </schema:Image>
        """
        # import pdb; pdb.set_trace()
        req = self.context.REQUEST

        base_url = self.context.absolute_url()
        img_url = base_url + '/image_large'

        portal_types = getToolByName(self.context, 'portal_types')
        props = getToolByName(self.context,
                              'portal_properties')['imaging_properties']
        sizes = props.getProperty('allowed_sizes')

        Image = resource.session.get_class(surf.ns.SCHEMA['Image'])

        img = Image(img_url)
        img.rdfs_label = 'depiction'
        # img.eea_fileInfo = img_url + "#fileInfo"

        st = ScaleTraverser(self.context, req)

        try:
            blob = st.fallback(req, 'image_large')
        except Exception as err:
            logger.exception(err)
            size = 0
        else:
            if isinstance(blob, basestring):
                size = len(blob)
            elif isinstance(blob, ImageScale):
                size = blob.data.getSize()
            else:
                size = blob.get_size()

        img.schema_contentSize = size

        icon = None
        fti = portal_types[self.context.portal_type]

        if fti.icon_expr:
            iconexpr = fti.icon_expr_object
            ec = getExprContext(self.context)
            icon_url = iconexpr(ec)
            icon = Image(icon_url)
            icon.rdfs_label = 'type_icon'
            icon.update()

        img.schema_thumbnail = []

        for size in sizes:
            name, info = size.split(' ')
            w, h = info.split(':')

            t = Image(self.context.absolute_url() + '/image_' + name)
            t.schema_width = str(w) + 'px'
            t.schema_height = str(h) + 'px'
            t.update()

            img.schema_thumbnail.append(t)

        img.update()

        if icon is not None:
            resource.foaf_depiction = [img, icon]
        else:
            resource.foaf_depiction = [img]

        resource.update()
        resource.save()
Ejemplo n.º 58
0
    def update(self):
        tool = api.portal.get_tool('portal_workflow')

        # Get the default workflow id
        chain = tool.getChainFor(self.context)
        if not chain:
            return

        # Get the current workflow state and workflow definition
        status = tool.getStatusOf(chain[0], self.context)
        wf = tool.getWorkflowById(chain[0])

        # Get currently available workflow actions (re-use from menu)
        actions = self.actions()

        # Evaluate "ploneintranet"-style "happy path metro map" from wf
        metro_expression = wf.variables.get('metromap_transitions')
        try:
            metro = metro_expression.default_expr(getExprContext(self.context))
        except AttributeError:
            metro = get_default_metromap(wf)
            # Fix issue where default metro missed the current state
            if status and status.get('review_state') not in [
                    step.get('state') for step in metro
            ]:
                metro = get_default_metromap(wf, status.get('review_state'))

        # Build data for our metro map
        forward = None
        backward = None
        future = False
        for step in metro:
            state = wf.states[step.get('state', wf.initial_state)]

            # Define CSS class
            classes = []  # [u'state-{0:s}'.format(state.id)]

            if 'className' in step:
                classes.append(step['className'])

            if future:
                classes.append('in-future')

            if status and state.id == status.get('review_state'):
                classes.append('active')
                future = True

            for action_id in step.get('reopen_transition', '').split(','):
                backward = backward or actions.get(action_id)

            self.steps.append({
                'title': state.title,
                'className': ' '.join(classes),
                'forward': forward,
                'backward': backward,
            })

            forward = None
            backward = None

            for action_id in step.get('next_transition', '').split(','):
                forward = forward or actions.get(action_id)

        if len(self.steps) < 2:
            self.steps = []