Example #1
0
    def setupContext(self, field_name, mode, widget, instance, field, \
                     accessor, **kwargs):

        # look for the context in the stack
        frame = sys._getframe()
        context = _marker
        while context is _marker and frame is not None:
            context = frame.f_locals.get('econtext', _marker)
            frame = frame.f_back
        if context is _marker:
            raise RuntimeError, 'Context not found'

        # for editing of multiple AT-based content at once we might want to
        # prefix the field-name.
        if 'fieldprefix' in kwargs:
            field_name = '%s%s' % (kwargs['fieldprefix'], field_name)

        widget = ImplicitAcquisitionWrapper(widget, instance)
        field = ImplicitAcquisitionWrapper(field, instance)
        context.setLocal('here', instance)
        context.setLocal('fieldName', field_name)
        context.setLocal('accessor', accessor)
        context.setLocal('widget', widget)
        context.setLocal('field', field)
        context.setLocal('mode', mode)
        context.setLocal('UID', instance.UID())

        if kwargs:
            for k, v in kwargs.items():
                context.setLocal(k, v)

        del frame
        return context
    def __call__(self, context):
        settings = IFeedSettings(context)
        wrapped = ImplicitAcquisitionWrapper(self, settings)

        generator = wrapped.get_terms()
        terms = tuple(generator)
        return SimpleVocabulary(terms)
Example #3
0
 def __of__(self, parent):
     '''
     Sneakily sets up the portal skin then returns the wrapper
     that Acquisition.Implicit.__of__() would return.
     '''
     w_self = ImplicitAcquisitionWrapper(aq_base(self), parent)
     w_self.setupCurrentSkin()
     return w_self
Example #4
0
 def __of__(self, parent):
     '''
     Sneakily sets up the portal skin then returns the wrapper
     that Acquisition.Implicit.__of__() would return.
     '''
     w_self = ImplicitAcquisitionWrapper(aq_base(self), parent)
     w_self.setupCurrentSkin()
     return w_self
Example #5
0
 def __of__(self, parent):
     '''
     Sneakily sets up the portal skin then returns the wrapper
     that Acquisition.Implicit.__of__() would return.
     '''
     w_self = ImplicitAcquisitionWrapper(self, parent)
     try:
         w_self.setupCurrentSkin()
     except ConflictError:
         raise
     except:
         # This shouldn't happen, even if the requested skin
         # does not exist.
         logger.exception("Unable to setupCurrentSkin()")
     return w_self
Example #6
0
 def __of__(self, parent):
     '''
     Sneakily sets up the portal skin then returns the wrapper
     that Acquisition.Implicit.__of__() would return.
     '''
     w_self = ImplicitAcquisitionWrapper(self, parent)
     try:
         w_self.setupCurrentSkin()
     except ConflictError:
         raise
     except:
         # This shouldn't happen, even if the requested skin
         # does not exist.
         logger.exception("Unable to setupCurrentSkin()")
     return w_self
 def __of__(self, parent):
     # Accesses the database, returning an acquisition
     # wrapper around the connected object rather than around self.
     try:
         return self._getOrOpenObject(parent)
     except:
         return ImplicitAcquisitionWrapper(self, parent)
Example #8
0
 def __of__(self, parent):
     '''
     Sneakily sets up the portal skin then returns the wrapper
     that Acquisition.Implicit.__of__() would return.
     '''
     w_self = ImplicitAcquisitionWrapper(self, parent)
     try:
         w_self.setupCurrentSkin()
     except:
         # This shouldn't happen, even if the requested skin
         # does not exist.
         import sys
         from zLOG import LOG, ERROR
         LOG('CMFCore', ERROR, 'Unable to setupCurrentSkin()',
             error=sys.exc_info())
     return w_self
Example #9
0
 def __of__(self, parent):
     try:
         self = ImplicitAcquisitionWrapper(self, parent)
         self._updateFromFS()
         return self
     except:
         logger.exception("Error during __of__")
         raise
Example #10
0
 def __of__(self, parent):
     try:
         self = ImplicitAcquisitionWrapper(self, parent)
         self._updateFromFS()
         return self
     except:
         logging.exception('FS Z SQL Method', 'Error during __of__')
         raise
Example #11
0
 def wrapped_context(self):
     """"We need to wrap the context to be able to acquire the root
         of the site to get tools, as done in plone.app.textfield"""
     context = self.context
     content = closest_content(context)
     if context.__class__ == dict:
         context = UserDict(self.context)
     return ImplicitAcquisitionWrapper(context, content)
Example #12
0
 def getHistoryMetadata(self, obj):
     """Returns the versioning metadata history.
     """
     self._assertAuthorized(obj, AccessPreviousVersions,
                            'getHistoryMetadata')
     portal_archivist = getToolByName(self, 'portal_archivist')
     hist = portal_archivist.getHistoryMetadata(obj)
     if hist:
         return ImplicitAcquisitionWrapper(hist, obj)
     return hist
    def __call__(self, context):

        try:
            utility = getUtility(IApiUtility, context=context)
        except ComponentLookupError:
            site = getSite()
            utility = getUtility(IApiUtility, context=site)
        else:
            utility = utility.__of__(context)

        wrapped = ImplicitAcquisitionWrapper(self, utility)

        generator = wrapped.get_terms()
        terms = tuple(generator)

        try:
            return SimpleVocabulary(terms)
        except ValueError as e:
            logger.info(e.message)
            return SimpleVocabulary([])
Example #14
0
    def __call__(self, context):

        try:
            utility = getUtility(IApiUtility, context=context)
        except ComponentLookupError:
            site = getSite()
            utility = getUtility(IApiUtility, context=site)
        else:
            utility = utility.__of__(context)

        wrapped = ImplicitAcquisitionWrapper(self, utility)

        generator = wrapped.get_terms()
        terms = tuple(generator)

        try:
            return SimpleVocabulary(terms)
        except ValueError as e:
            logger.info(e.message)
            return SimpleVocabulary([])
Example #15
0
 def __of__(self, parent):
     try:
         self = ImplicitAcquisitionWrapper(self, parent)
         self._updateFromFS()
         return self
     except:
         import sys
         LOG('FS Z SQL Method',
             ERROR,
             'Error during __of__',
             error=sys.exc_info())
         raise
Example #16
0
 def wrapped_context(self):
     context = self.context
     content = closest_content(context)
     # We'll wrap context in the current site *if* it's not already
     # wrapped.  This allows the template to acquire tools with
     # ``context/portal_this`` if context is not wrapped already.
     # Any attempts to satisfy the Kupu template in a less idiotic
     # way failed. Also we turn dicts into UserDicts to avoid
     # short-circuiting path traversal. :-s
     if context.__class__ == dict:
         context = UserDict(self.context)
     return ImplicitAcquisitionWrapper(context, content)
Example #17
0
 def lookupType(self, package, type):
     types = self.listRegisteredTypes()
     for t in types:
         if t['package'] != package:
             continue
         if t['meta_type'] == type:
             # We have to return the schema wrapped into the acquisition of
             # something to allow access. Otherwise we will end up with:
             # Your user account is defined outside the context of the object
             # being accessed.
             t['schema'] = ImplicitAcquisitionWrapper(t['schema'], self)
             return t
     return None
Example #18
0
 def delegate(self, method, obj, data=None, file=None, **kw):
     if file is not None:
         kw['file'] = file
     __traceback_info__ = (method, obj, kw)
     context = getContext(obj, kw.get('REQUEST'))
     if context is not obj:
         # If the object is being created by means of a PUT
         # then it has no context, and some of the stuff
         # we are doing here may require a context.
         # Wrapping it in an ImplicitAcquisitionWrapper should
         # be safe as long as nothing tries to persist
         # a reference to the wrapped object.
         obj = ImplicitAcquisitionWrapper(obj, context)
     tool = getToolByName(obj, TOOL_ID, None)
     components = None
     if tool is not None:
         info = kw.copy()
         info['data'] = data
         info['mode'] = method
         components = tool.getMarshallersFor(obj, **info)
     else:
         # Couldn't find a context to get
         # hold of the tool or the tool is not installed.
         logger.log(
             logging.DEBUG, 'Could not find the marshaller tool. '
             'It might not be installed or you might not '
             'be providing enough context to find it.')
     # We just use the first component, if one is returned.
     if components:
         marshaller = getComponent(components[0])
     else:
         # If no default marshaller was provided then we complain.
         if self.fallback is None:
             raise MarshallingException(
                 "Couldn't get a marshaller for %r, %r" % (obj, kw))
         # Otherwise, use the default marshaller provided. Note it
         # must be an instance, not a factory.
         marshaller = self.fallback
     __traceback_info__ = (marshaller, method, obj, kw)
     args = (obj, )
     if method == 'demarshall':
         args += (data, )
     method = getattr(marshaller, method)
     return mapply(method, *args, **kw)
 def manage_main(self, REQUEST, *a, **kw):
     """
     Wrap Folder's manage_main to render international characters
     """
     # ugh, API cruft
     if REQUEST is self and a:
         REQUEST = a[0]
         a = a[1:]
     # wrap the special dtml method Folder.manage_main into a valid
     # acquisition context. Required for Zope 2.8+.
     try:
         r = Folder.manage_main(self, self, REQUEST, *a, **kw)
     except AttributeError:
         manage_main = ImplicitAcquisitionWrapper(Folder.manage_main, self)
         r = manage_main(self, self, REQUEST, *a, **kw)
     if isinstance(r, unicode):
         r = r.encode('utf-8')
     REQUEST.RESPONSE.setHeader('Content-type', 'text/html; charset=utf-8')
     return r
Example #20
0
    def __init__(self, kw, context):
        self.context = ImplicitAcquisitionWrapper(self, context)
        self.url = kw['path']
        self.title = kw['title']
        self.description = u''

        tzname = "Europe/Brussels"
        zone = timezone(tzname)
        self.start = isotime2dt(kw['start_date'], zone)
        self.end = isotime2dt(kw['end_date'], zone)
        self.timezone = tzname

        self.location = kw.get('City', '')
        self.attendees = kw['number_of_attendees']  # not used anyway
        self.contact_name = kw['agency_initial_contact']
        self.contact_email = kw['agency_contact_reply']
        self.contact_phone = ""
        self.event_url = kw['website_of_event']
        self.subjects = ", ".join(kw['category'].split("\\n"))
        self.text = kw['body']
        self.organiser = kw['organization']
        self.attachment = False
Example #21
0
 def __of__(self, parent):
     w, m, p = self._ugh
     return m.__of__(ImplicitAcquisitionWrapper(w, parent))
Example #22
0
 def __call__(self, *args, **kw):
     w, m, parent = self._ugh
     self = m.__of__(ImplicitAcquisitionWrapper(w, parent))
     return self(*args, **kw)
Example #23
0
 def __call__(self, form, request):
     template = self.template
     if IAcquirer.providedBy(template):
         return ImplicitAcquisitionWrapper(template, form)
     else:
         return template
Example #24
0
 def getContent(self):
     content = super(ControlPanelEditForm, self).getContent()
     return ImplicitAcquisitionWrapper(content, self.context)
Example #25
0
 def create(self, data):
     container = aq_inner(self.context)
     content = self.ti.factory(**data)
     content.__parent__ = container
     content = ImplicitAcquisitionWrapper(content, container)
     return content
Example #26
0
 def Schema(self):
     schema = self.getAndPrepareSchema()
     return ImplicitAcquisitionWrapper(schema, self)
Example #27
0
class ListSubscribeForm(SubscribeForm):

    # See Products.PloneHotfix20160830==1.3
    allow_prefill_from_GET_request = True

    @property
    def fields(self):
        fields = field.Fields()
        settings = IFeedSettings(self.context)

        # Javascript-widget
        if settings.enable_select_all:
            fields += field.Fields(
                SelectAllGroupsJavascript(schema.Field(__name__="js",
                                                       required=False),
                                          mode="hidden"))

        # Include form fields, but change the order around.
        fields += field.Fields(ISubscription).select('interests')
        fields['interests'].widgetFactory = InterestsWidget.factory

        if settings.show_name:
            fields += field.Fields(
                schema.TextLine(
                    __name__="name",
                    title=_(u"Name"),
                    required=False,
                ))

        fields += field.Fields(ISubscription).select('email')

        # Add mailinglist as hidden field
        fields += field.Fields(schema.ASCII(__name__="list_id", required=True),
                               mode="hidden")

        context = self.getContent()
        api = getUtility(IApiUtility, context=self.context)
        result = api.list_merge_vars(context.mailinglist)

        for entry in result:
            name = entry['tag'].lower()

            if name in fields:
                continue

            if not entry['show']:
                continue

            # Skip all-uppercase:
            if entry['name'] == entry['name'].upper():
                continue

            field_type = entry['field_type']
            required = entry['req']

            if field_type == 'text':
                factory = schema.TextLine
                options = {}

            elif field_type == 'dropdown':
                factory = schema.Choice
                choices = list(entry['choices'])

                if not required:
                    choices.append(u"")
                    required = True

                options = {
                    'vocabulary':
                    SimpleVocabulary([
                        SimpleTerm(value=value,
                                   token=value.encode('ascii',
                                                      'xmlcharrefreplace'),
                                   title=value or _(u"None"))
                        for value in choices
                    ])
                }

            else:
                continue

            fields += field.Fields(
                factory(__name__=name.encode('utf-8'),
                        default=entry['default'],
                        required=required,
                        title=_(entry['name']),
                        **options))

        return fields

    # Remove prefix; we want to be able to provide defaults using a
    # simple format.
    prefix = ""

    @property
    def description(self):
        context = self.context.aq_base
        if self.request.get('success'):
            return u''
        elif not IPloneSiteRoot.providedBy(context) \
                 and context.Description():
            return context.Description()
        else:
            return _(u"Select subscription options and submit form.")

    @property
    def label(self):
        if self.request.get('success'):
            return _(u"Request processed")

        name = self.getContent().name
        return _(u"Subscribe to: ${name}", mapping={'name': name})

    @view.memoize
    def getContent(self):
        if ISubscriptionFormSettings.providedBy(self.context):
            return self.context

        settings = IFeedSettings(self.context)
        try:
            context = SubscribeContext(self.request)
        except KeyError, exc:
            raise BadRequest(u"Missing parameter: %s." % exc)

        return context.__of__(
            ImplicitAcquisitionWrapper(settings, self.context))
Example #28
0
 def Schema(self):
     """Return a (wrapped) schema instance for this object instance.
     """
     return ImplicitAcquisitionWrapper(ISchema(self), self)
 def __of__(self, parent):
     self = ImplicitAcquisitionWrapper(self, parent)
     self._updateFromFS()
     return self
Example #30
0
 def _wrap_schema(self, schema):
     return ImplicitAcquisitionWrapper(schema, self)
Example #31
0
    def wrapObject(self, object, sql_catalog_id=None, **kw):
        """
          Return a wrapped object for reindexing.
        """
        catalog = self.getSQLCatalog(sql_catalog_id)
        if catalog is None:
            # Nothing to do.
            LOG('wrapObject', 0, 'Warning: catalog is not available')
            return (None, None)

        document_object = aq_inner(object)
        w = IndexableObjectWrapper(document_object)

        wf = getToolByName(self, 'portal_workflow')
        if wf is not None:
            w.__dict__.update(wf.getCatalogVariablesFor(object))

        # Find the parent definition for security
        is_acquired = 0
        while getattr(document_object, 'isRADContent', 0):
            # This condition tells which object should acquire
            # from their parent.
            # XXX Hardcode _View_Permission for a performance point of view
            if getattr(aq_base(document_object), '_View_Permission', ACQUIRE_PERMISSION_VALUE) == ACQUIRE_PERMISSION_VALUE\
               and document_object._getAcquireLocalRoles():
                document_object = document_object.aq_parent
                is_acquired = 1
            else:
                break
        if is_acquired:
            document_w = IndexableObjectWrapper(document_object)
        else:
            document_w = w

        (security_uid_dict, optimised_roles_and_users) = \
              catalog.getSecurityUidDict(document_w)

        w.optimised_roles_and_users = optimised_roles_and_users

        catalog_security_uid_groups_columns_dict = \
            catalog.getSQLCatalogSecurityUidGroupsColumnsDict()
        default_security_uid_column = catalog_security_uid_groups_columns_dict[
            '']
        for local_roles_group_id, security_uid in security_uid_dict.items():
            catalog_column = catalog_security_uid_groups_columns_dict.get(
                local_roles_group_id, default_security_uid_column)
            setattr(w, catalog_column, security_uid)

        # XXX we should build vars begore building the wrapper

        predicate_property_dict = catalog.getPredicatePropertyDict(object)
        if predicate_property_dict is not None:
            w.predicate_property_dict = predicate_property_dict
        else:
            w.predicate_property_dict = {}

        (subject_set_uid,
         optimised_subject_list) = catalog.getSubjectSetUid(document_w)
        w.optimised_subject_list = optimised_subject_list
        w.subject_set_uid = subject_set_uid

        return ImplicitAcquisitionWrapper(w, aq_parent(document_object))
 def getContent(self):
     return ImplicitAcquisitionWrapper(ControlPanelAdapter(self.context),
                                       self.context)
Example #33
0
 def vocabulary(self):
     settings = IFeedSettings(self.context)
     return ImplicitAcquisitionWrapper(interest_groups_factory, settings)
Example #34
0
 def __getattr__(self, name):
     w, m, parent = self._ugh
     self = m.__of__(ImplicitAcquisitionWrapper(w, parent))
     return getattr(self, name)