Beispiel #1
0
    def _purgePortlets(self):
        """Unregister all portlet managers and portlet types, and remove
        portlets assigned to the site root
        """

        # Purge portlet types

        registeredPortletTypes = [r.name for r in self.context.registeredUtilities()
                                        if r.provided == IPortletType]

        for name, portletType in getUtilitiesFor(IPortletType):
            if name in registeredPortletTypes:
                self.context.unregisterUtility(provided=IPortletType, name=name)

        # Purge portlets assigned to the site root
        site = self.environ.getSite()

        for name, portletManager in getUtilitiesFor(IPortletManager):
            assignable = queryMultiAdapter((site, portletManager), IPortletAssignmentMapping)
            if assignable is not None:
                for key in list(assignable.keys()):
                    del assignable[key]

        # Purge portlet manager registrations - this will also get rid of
        # global portlet registrations, since these utilities disappear

        portletManagerRegistrations = [r for r in self.context.registeredUtilities()
                                        if r.provided.isOrExtends(IPortletManager)]

        for registration in portletManagerRegistrations:
            self.context.unregisterUtility(provided=registration.provided,
                                           name=registration.name)
Beispiel #2
0
 def fields(self):
     counts = Counter(
         [id(reg) for name, reg in getUtilitiesFor(IBehavior)]
     )
     fields = []
     for name, reg in getUtilitiesFor(IBehavior):
         if name in TTW_BEHAVIOR_BLACKLIST:
             # skip blacklisted
             continue
         with_name = counts[id(reg)] > 1
         if with_name and reg.name != name:
             continue
         fname = reg.name if reg.name else name
         if six.PY2 and isinstance(fname, six.text_type):
             fname = fname.encode('utf8')
         fields.append(
             schema.Bool(
                 __name__=fname,
                 title=reg.title,
                 description=reg.description,
                 required=False
             )
         )
     form_fields = field.Fields(*sorted(fields, key=attrgetter('title')))
     for ff in form_fields.values():
         ff.widgetFactory = SingleCheckBoxFieldWidget
     return form_fields
Beispiel #3
0
    def roles(self):
        """Get a list of roles that can be managed.
        
        Returns a list of dics with keys:
        
            - id
            - title
        """
        context = aq_inner(self.context)
        portal_membership = getToolByName(context, 'portal_membership')
        
        pairs = []

        #check to see if OpenOCW installed
        portal_setup = self.aq_parent.portal_setup
        if 'openOCW-final' in portal_setup.getImportStepRegistry().listSteps():
            #user default sharing page roles
            for name, utility in getUtilitiesFor(ISharingPageRole):
                permission = utility.required_permission
                if permission is None or portal_membership.checkPermission(permission, context):
                    pairs.append(dict(id = name, title = utility.title))
        else:
            #use eduCommons sharing page roles
            for name, utility in getUtilitiesFor(IeduCommonsSharingPageRole):
                permission = utility.required_permission
                if permission is None or portal_membership.checkPermission(permission, context):
                    pairs.append(dict(id = name, title = utility.title))

        pairs.sort(lambda x, y: cmp(x['id'], y['id']))
        return pairs
 def getData(self):
     data = dict()
     data["Report Date"] = datetime.utcnow().isoformat()
     for name, utilClass in getUtilitiesFor(ICallHomeCollector):
         chData = utilClass().generateData()
         if chData:
             data.update(chData)
     if self._master:
         for name, utilClass in getUtilitiesFor(IMasterCallHomeCollector):
             chData = utilClass().generateData(self._dmd)
             if chData:
                 data.update(chData)
     return data
    def _apply_digest(self, site, storage, digest_info):
        """Filter digest info using registered filters
           apply registered strategies for user with filtered info
        """
        filter_rules = [r[1] for r in getUtilitiesFor(IDigestFilterRule)]
        digest_strategies = [r[1] for r in getUtilitiesFor(IDigestAction)]

        for subscriber, info in digest_info.items():
            for rule in filter_rules:
                info = rule(site, subscriber, info)

            for action in digest_strategies:
                action(site, storage, subscriber, info)
Beispiel #6
0
def _signalToContextDict(signal, zopeurl, notification=None, guidManager=None):
    summary = signal.event
    # build basic event context wrapper for notifications
    if signal.clear:
        # aged and closed events have clear == True, but they don't have an associated clear event
        #   spoof a clear event in those cases, so the notification messages contain useful info
        if summary.status == zep_pb2.STATUS_AGED:
            occur = signal.clear_event.occurrence.add()
            occur.summary = "Event aging task aged out the event."
            summary.cleared_by_event_uuid = "Event aging task"
        elif summary.status == zep_pb2.STATUS_CLOSED:
            occur = signal.clear_event.occurrence.add()
            
            # once an event is in a closed state, the ownerid (current_user_name) is removed
            # determine who closed the event by extracting the most recent user_name in the event's audit_log
            last_audit_entry = max(signal.event.audit_log, key=lambda x:x.timestamp)
            summary.current_user_name = last_audit_entry.user_name
            
            occur.summary = "User '" + summary.current_user_name + "' closed the event in the Zenoss event console."
            summary.cleared_by_event_uuid = "User action"
        data = NotificationEventContextWrapper(summary, signal.clear_event)
    else:
        data = NotificationEventContextWrapper(summary)

    # add urls to event context
    data['urls']['eventUrl'] = getEventUrl(zopeurl, summary.uuid)
    data['urls']['ackUrl'] = getAckUrl(zopeurl, summary.uuid)
    data['urls']['closeUrl'] = getCloseUrl(zopeurl, summary.uuid)
    proxy = EventSummaryProxy(summary)
    data['urls']['deviceUrl'] = _getBaseDeviceUrl(zopeurl, proxy.DeviceClass, proxy.device)
    data['urls']['eventsUrl'] = getEventsUrl(zopeurl, proxy.DeviceClass, proxy.device)
    data['urls']['reopenUrl'] = getReopenUrl(zopeurl, summary.uuid)
    data['urls']['baseUrl'] = zopeurl
    # now process all custom processors that might be registered to enhance
    # the event context
    for key, processor in getUtilitiesFor(IProcessSignal):
        data[key] = processor.process(signal)

    # Process INotificationContextProvider
    for key, contextProvider in getUtilitiesFor(INotificationContextProvider):
        contextProvider.updateContext(signal, data)

    # Add trigger and notification info
    if notification:
        data['notification']['name'] = notification.titleOrId()
    if guidManager:
        trigger = guidManager.getObject(signal.trigger_uuid)
        if trigger:
            data['trigger']['name'] = trigger.titleOrId()

    return data
Beispiel #7
0
def nonfolderish_possible_descriptors(context):
    portal_type = getattr(aq_inner(context), 'portal_type', None)
    if portal_type is None:
        return PossibleDescriptors()

    all = getUtilitiesFor(\
          interfaces.IContentTypeDescriptor)
    all = set([(n, c) for n, c in all])
    folderish = getUtilitiesFor(\
          interfaces.IFolderishContentTypeDescriptor)
    folderish = set([(n, c) for n, c in folderish])

    return PossibleDescriptors(list(all.difference(folderish)),
                               'nonfolderish')
def connect_all(event=None):
    """Connect all connections, which have related utilities registered"""

    # Notify all, who want to register callbacks for connections
    notify(BeforeBrokerConnectEvent())

    # Gather all producer and consumer utility registrations
    from collective.zamqp.interfaces import IProducer, IConsumer
    regs = list(getUtilitiesFor(IProducer)) + list(getUtilitiesFor(IConsumer))

    # Connect all connections, which have related utilities registered
    for connection_id, connection in getUtilitiesFor(IBrokerConnection):
        if filter(lambda reg: reg[1].connection_id == connection_id, regs):
            connection.connect()
def get_nsmap():
    schema_metadata_handlers = tuple(
        getUtilitiesFor(ISchemaMetadataHandler)
    )
    field_metadata_handlers = tuple(
        getUtilitiesFor(IFieldMetadataHandler)
    )

    nsmap = {}
    metadata_handlers = schema_metadata_handlers + field_metadata_handlers
    for name, handler in metadata_handlers:
        namespace, prefix = handler.namespace, handler.prefix
        if namespace is not None and prefix is not None:
            nsmap[prefix] = namespace
    return nsmap
Beispiel #10
0
    def test_provideConnection(self):

        conns = list(getUtilitiesFor(IZopeDatabaseAdapter))
        self.assertEqual(conns, [])
        connectionstub = queryUtility(IZopeDatabaseAdapter, 'stub')
        self.assertEqual(connectionstub, None)

        self.context = xmlconfig.file("rdb.zcml", zope.rdb.tests)
        connectionstub = queryUtility(IZopeDatabaseAdapter, 'stub')
        connection = connectionstub()
        self.assertEqual(connectionstub.__class__, DAStub)
        conns = getUtilitiesFor(IZopeDatabaseAdapter)
           
        self.assertEqual([c[0] for c in conns], ["stub"])
        self.assertEqual(connection.__class__, ZopeConnection)
    def initialize(self, context, request):
        """ called by the API Framework
        """
        logger.info("DefaultRouter.initialize: context=%r request=%r" % (context, request))

        self.context = context
        self.request = request

        self.environ = request.environ
        self.http_host = request["HTTP_HOST"]
        self.url = request.getURL()

        if self.is_initialized:
            return

        logger.info("DefaultRouter::initialize")
        for name, provider in component.getUtilitiesFor(IRouteProvider):
            logger.info("DefaultRouter::initialize: name=%s, provider=%r", name, provider)

            if getattr(provider, "initialize", None):
                provider.initialize(context, request)

            for route in provider.routes:
                self.add_url_rule(*route)

        self.is_initialized = True
Beispiel #12
0
def get_all_user_properties(user):
    """
        Returns a mapping with all the defined user profile properties and its values.

        The properties list includes all properties defined on any profile extension that
        is currently registered. For each of this properties, the use object is queried to
        retrieve the value. This may result in a empty value if that property is not set, or
        the value of the property provided by any properties PAS plugin.

        NOTE: Mapped LDAP atrributes will be retrieved and returned on this mapping if any.

    """
    user_properties_utility = getUtility(ICatalogFactory, name='user_properties')
    attributes = user_properties_utility.properties + METADATA_USER_ATTRS
    try:
        extender_name = api.portal.get_registry_record('genweb.controlpanel.core.IGenwebCoreControlPanelSettings.user_properties_extender')
    except:
        extender_name = ''

    if extender_name:
        if extender_name in [a[0] for a in getUtilitiesFor(ICatalogFactory)]:
            extended_user_properties_utility = getUtility(ICatalogFactory, name=extender_name)
            attributes = attributes + extended_user_properties_utility.properties

    mapping = {}
    for attr in attributes:
        value = user.getProperty(attr)
        if isinstance(value, str) or isinstance(value, unicode):
            mapping.update({attr: value})

    return mapping
Beispiel #13
0
def quizz_choice(context):
    terms = []
    utils = getUtilitiesFor(IQuizz)
    for name, quizz in utils:
        if check_quizz(name, quizz, context):
            terms.append(SimpleTerm(value=name, title=quizz.__title__))
    return SimpleVocabulary(terms)
 def get_delivery_services(self):
     result = atapi.DisplayList()
     result.add(u'mailhost', _(u'EasyNewsletter_label_PloneMailHost', u'Default Plone Mailhost'))
     for utility in getUtilitiesFor(IMailHost):
         if utility[0]:
             result.add(utility[0], utility[0])
     return result
Beispiel #15
0
 def items(self):
     results = [(name, TypeInterface(iface, self, name))
                for name, iface in getUtilitiesFor(IInterface)
                if iface.extends(IInterface)]
     results.sort(lambda x, y: cmp(x[1].interface.getName(),
                                   y[1].interface.getName()))
     return results
Beispiel #16
0
    def roles(self):
        """Get a list of roles that can be managed.

        Returns a list of dicts with keys:

            - id
            - title
        """
        context = self.context
        portal_membership = getToolByName(context, 'portal_membership')

        pairs = []

        for name, utility in getUtilitiesFor(ISharingPageRole):
            permission = utility.required_permission
            if permission is not None:
                if not portal_membership.checkPermission(permission, context):
                    continue
            # be friendly to utilities implemented without required_interface
            iface = getattr(utility, 'required_interface', None)
            if iface is not None and not iface.providedBy(context):
                continue
            pairs.append(dict(id = name, title = utility.title))

        pairs.sort(key=lambda x: normalizeString(translate(x["title"], context=self.request)))
        return pairs
    def update_vocabulary(self, vocab):
        site = getSite()
        path = '/'.join(vocab.getPhysicalPath())
        logger.info("Updating dynamic vocabulary: %s" % path)

        vocab_id = vocab.vocabulary_id

        registered_vocabs = [i[0] for i in getUtilitiesFor(IVocabularyFactory)]

        if not vocab_id:
            logger.warn(
                "This vocabulary was not registered, you need to register "
                "it first."
            )
            return False

        elif vocab_id not in registered_vocabs:
            logger.warn("There is no vocabulary registered with id: %s"
                        % vocab_id)
            return False

        vocabulary = queryUtility(IVocabularyFactory, vocab_id, context=site)

        vocabulary.clearTerms()

        for child in vocab.getChildNodes():
            vocabulary.addTerm(child)

        sm = site.getSiteManager()
        sm.registerUtility(vocabulary, IVocabularyFactory, vocab_id)
        logger.info("Vocabulary updated.")

        return True
Beispiel #18
0
def get_tax_handler_vocab(context):
    terms = []
    for name, utility in sorted(
            getUtilitiesFor(ITaxHandler), key=lambda x: x[1].label):
        terms.append(
            SimpleTerm(value=name, token=name, title=utility.label))
    return SimpleVocabulary(terms)
Beispiel #19
0
    def conditions(self):
        conditions = {}
        for name, utility in getUtilitiesFor(IRuleCondition):
            conditions[name] = utility

        return self._populate_info(self.context.conditions,
                                   conditions, 'condition')
def principalInfoStorages(context):
    terms = []
    for name, storage in getUtilitiesFor(IPrincipalInfoStorage):
        terms.append((storage.name, SimpleTerm(name, name, storage.name)))

    terms.sort()
    return SimpleVocabulary([term for n, term in terms])
Beispiel #21
0
    def guessBody(self, table, header, output):
        """ Discover column types from table body
        """
        utilities = getUtilitiesFor(IGuessType)
        utilities = sorted(utilities, cmp=compare)

        missing = self.missing

        for row in table:
            for index, cell in enumerate(row):
                # Skip missing values
                if cell.lower().strip() in missing:
                    continue

                label = header[index]
                title, columnType = self.column_type(label)

                # Type in header, skip this column
                if columnType:
                    continue

                output.setdefault(title, {})
                for name, guess in utilities:
                    if guess(cell, label):
                        output[title].setdefault(name, guess.priority)
                        output[title][name] += 1
Beispiel #22
0
def availableFormat():
    """Return a vocabulary of the available formats.
    """
    results = []
    for name, format in component.getUtilitiesFor(ITextFormat):
        results.append(SimpleTerm(value=name, title=format.title))
    return SimpleVocabulary(results)
Beispiel #23
0
def lookup_behavior_registration(
        name=None, identifier=None, warn_about_fallback=True):
    """Look up behavior registration either by name or interface identifier.
       Fall back to checking the former_dotted_names if the lookup is not
       successful.

    ``ValueError`` is thrown if function call is incomplete.
    ``BehaviorRegistrationNotFound`` is thrown if lookup fails.
    """
    try:
        assert(name or identifier)
    except AssertionError:
        raise ValueError('Either ``name`` or ``identifier`` must be given')
    # identifier rules if given
    if identifier:
        name = identifier
    try:
        return getUtility(IBehavior, name=name)
    except ComponentLookupError:
        for id_, behavior in getUtilitiesFor(IBehavior):
            # Before we raise an error, iterate over all behaviors and check
            # if the requested name is registered as a former dotted name.
            if name in behavior.former_dotted_names:
                if warn_about_fallback:
                    logger.warn(
                        'The dotted name "{0}" is deprecated. It has been '
                        'changed to "{1}"'.format(
                            name, behavior.interface.__identifier__, ))
                return behavior
        raise BehaviorRegistrationNotFound(name)
 def show_quickupload_action(self):
     portal = getUtility(IPloneSiteRoot)
     qup_prefs = IQuickUploadControlPanel(portal)
     if not qup_prefs.show_upload_action:
         return False
     context_state = getMultiAdapter(
         (aq_inner(self.context), self.request),
         name=u'plone_context_state')
     if not (
             context_state.is_default_page() or
             context_state.is_folderish()):
         return False
     # If the Quickuploader portlet is shown in the current context, don't
     # show the Upload action, since the portlet takes precedence
     portlet_managers = [
         x[1] for x in getUtilitiesFor(IPortletManager)
         if not x[0].startswith('plone.dashboard')
     ]
     for mgr in portlet_managers:
         retriever = getMultiAdapter((self.context, mgr), IPortletRetriever)
         portlets = retriever.getPortlets()
         for portlet in portlets:
             if IQuickUploadPortlet.providedBy(portlet["assignment"]):
                 return False
     return True
Beispiel #25
0
 def get(self, section, name=None):
     utils = getUtilitiesFor(IConfiguration)
     for utilid, util in utils:
         if utilid:
             res = util.get(section, name)
             if res:
                 return res
Beispiel #26
0
    def listContentTypes(self):
        cts = []
        for name, ct in getUtilitiesFor(ISchemaAware):
            cts.append((ct.title, ct))

        cts.sort()
        return [ct for _t, ct in cts]
def FieldsVocabularyFactory(context):
    field_factories = getUtilitiesFor(IFieldFactory)
    terms = []
    for (field_id, factory) in field_factories:
        terms.append(SimpleVocabulary.createTerm(factory, translate(factory.title), factory.title))

    return SimpleVocabulary(terms)
Beispiel #28
0
    def render(self):
        # Test that our installation was successful
        pau = queryUtility(IAuthentication)
        if pau is None or type(pau) is not PluggableAuthenticatorPlugin:
            if pau is not None:
                st = "PAU not installed correctly: %s" % pau
                utilities = getUtilitiesFor(IAuthentication)
                st += "\n Available utilities are: %s" % [u for u in utilities]
                return st
            else:
                return "PAU Utility not found"

        st = ('Success: Credentials plugins= %s; Authenticator plugins= %s' %
                (pau.credentialsPlugins, pau.authenticatorPlugins))
        roleMgr = IPrincipalRoleManager(self.context)
        p = roleMgr.getPrincipalsForRole('gfn.Administrator')
        st += "\n  Administrators: %s" %p
        for ut in pau.credentialsPlugins:
            if queryUtility(ICredentialsPlugin, name=ut) is None:
                st += '\n     Could not find credentials plugin for %s' % ut
        for ut in pau.authenticatorPlugins:
            if queryUtility(IAuthenticatorPlugin, name=ut) is None:
                st += '\n     Could not find authenticator plugin for %s' % ut

        return st
    def results(self, start, until=None):
        today = DateTime()
        today = DateTime(today.year(), today.month(), today.day())
        start = DateTime(start)
        start = DateTime(start.year(), start.month(), start.day())

        query = Indexed('chimpfeeds') & \
                In('review_state', ('published', )) & \
                Ge('feedSchedule', start)

        if until:
            try:
                until = DateTime(until)
            except DateTime.SyntaxError:
                pass
            else:
                query = query & Le('feedSchedule', until)

        site = getToolByName(self.context, "portal_url").getPortalObject()
        settings = IFeedSettings(site)
        if settings.use_moderation:
            query = query & Eq('feedModerate', True)

        catalog = getToolByName(self.context, "portal_catalog")

        extras = []
        utilities = getUtilitiesFor(IGroupExtras)
        groups = InterestGroupVocabulary()(self.context)
        for name, util in utilities:
            for group in groups:
                extras.extend(util.items(group.title, start, until))

        return list(catalog.evalAdvancedQuery(
            query, (('feedSchedule', 'desc'), ))) + extras
Beispiel #30
0
 def get_actions(self):
     actions = []
     for name, Utility in getUtilitiesFor(IStructureAction):
         utility = Utility(self.context, self.request)
         actions.append(utility)
     actions.sort(key=lambda a: a.order)
     return [a.get_options() for a in actions]
def FieldsVocabularyFactory(context):
    field_factories = getUtilitiesFor(IFieldFactory)
    terms = []
    for (field_id, factory) in field_factories:
        terms.append(
            SimpleVocabulary.createTerm(factory, translate(factory.title),
                                        factory.title))

    return SimpleVocabulary(terms)
 def get_subscriber_sources(self):
     result = atapi.DisplayList()
     result.add(
         u'default',
         _(u'EasyNewsletter_label_noSource',
           u'no external subscriber source'))
     for utility in getUtilitiesFor(ISubscriberSource):
         result.add(utility[0], utility[0])
     return result
    def plugins(self):
        terms = []
        registered = dict(getUtilitiesFor(IPlugin))
        keys = registered.keys()
        keys.sort()
        for key in keys:
            terms.append(SimpleTerm(key, title=key))

        return SimpleVocabulary(terms)
 def _enable_all_plugins(self):
     from plone.registry.interfaces import IRegistry
     from sc.social.like.plugins.interfaces import IPlugin
     from zope.component import getUtilitiesFor
     from zope.component import getUtility
     registry = getUtility(IRegistry)
     settings = registry.forInterface(ISocialLikeSettings)
     all_plugins = tuple(i[0] for i in getUtilitiesFor(IPlugin))
     settings.plugins_enabled = all_plugins
    def _getUtilitiesFor(self, iface):
        """ return everything registered for an interface """

        try:
            from zope.app import zapi
            return zapi.getUtilitiesFor(iface)
        except ImportError:
            from zope.component import getUtilitiesFor
            return getUtilitiesFor(iface)
Beispiel #36
0
def get_import_type(data, path, *args):
    types = getUtilitiesFor(IImportType)
    _types = {name: klass for name, klass in types}
    if data['portal_type'] in _types:
        return _types[data['portal_type']](data, path, *args)
    logger.info(
        'No explicit mapping for type {type}.'
        ' Attempting base import type.'.format(type=data['portal_type']))
    return BaseImportType(data, path, *args)
Beispiel #37
0
def _load_utilities(utility_class):
    """
    Loads ZCA utilities of the specified class.

    @param utility_class: The type of utility to load.
    @return: A list of utilities, sorted by their 'weight' attribute.
    """
    utilities = (f for n, f in getUtilitiesFor(utility_class))
    return sorted(utilities, key=lambda f: getattr(f, 'weight', 100))
Beispiel #38
0
def parseWorkerOptions(options):
    dispatchFilterName = options.get('configDispatch', '') if options else ''
    filterFactories = dict(getUtilitiesFor(IConfigurationDispatchingFilter))
    filterFactory = filterFactories.get(dispatchFilterName, None) or \
                    filterFactories.get('', None)
    if filterFactory:
        filter = filterFactory.getFilter(options)
        log.debug("Filter configured: %s:%s", filterFactory, filter)
        return filter
def EasyFormActionsVocabularyFactory(context):
    """EasyForm actions vocabulary"""
    from collective.easyform.interfaces import IActionFactory
    return SimpleVocabulary([
        SimpleVocabulary.createTerm(factory, translate(factory.title),
                                    factory.title)
        for (id, factory) in getUtilitiesFor(IActionFactory)
        if factory.available(context)
    ])
Beispiel #40
0
    def reload(self):
        """
        Read in tooltips from XML files.
        """
        def _load_tips(doc, lang, view):
            for tip in doc.getElementsByTagName('tooltip'):
                d = {}
                for node in tip.childNodes:
                    if isinstance(node, minidom.Text): continue
                    result = _valpat.search(node.toxml())
                    if result:
                        value = result.groups()[0].strip()
                        name = node.tagName
                        if name in _tipattrs and _tipattrs[name] != str:
                            value = eval(value)
                        if isinstance(value, basestring):
                            value = value.replace('%26', '&')
                        d[name] = value
                if 'autoHide' in d:
                    d['closable'] = not d['autoHide']
                self.add(lang, view, d)

        def _load_navhelp(doc, lang):
            for tip in doc.getElementsByTagName('pagehelp'):
                result = _valpat.search(tip.toxml())
                target = tip.getAttribute('target')
                title = tip.getAttribute('title')
                if result and target:
                    value = result.groups()[0].strip()
                    self._add_navhelp(lang, target, title, value)

        def _load_files(_none, path, fnames):
            lang = path.rsplit('/', 1)[-1]
            for f in fnames:
                if not f.endswith('.xml'):
                    continue
                view = f[:-4]
                fd = open(os.path.join(path, f))
                data = fd.read()
                fd.close()
                doc = minidom.parseString(data.replace('&', '%26'))
                if f.startswith('nav-help'):
                    _load_navhelp(doc, lang)
                else:
                    _load_tips(doc, lang, view)
                doc.unlink()

        os.path.walk(_datapath, _load_files, None)

        # Now load up other tooltips.  The last one to override wins.
        # Processed by name in alphabetical order
        for name, klass in \
                sorted(component.getUtilitiesFor(ITooltipProvider), key=lambda tup: tup[0]):
            log.debug('Loading tooltip provider %s (%s)', name, klass)
            os.path.walk(klass().path(), _load_files, None)
        self._reloaded = True
Beispiel #41
0
class CallHomeData(object):
    def __init__(self, dmd=None, master=True):
        self._dmd = dmd
        self._master = master

    def getExistingVersionHistories(self):
        versionHistories = {}
        if self._dmd:
            try:
                metricsString = self._dmd.callHome.metrics
                if metricsString and metricsString.strip():
                    metricsObj = json.loads(metricsString)
                    versionHistories = metricsObj.get(VERSION_HISTORIES_KEY,
                                                      {})
            except AttributeError:
                pass
        return {VERSION_HISTORIES_KEY: versionHistories}

    def getData(self):
        data = dict()
        errors = []
        data[REPORT_DATE_KEY] = datetime.utcnow().isoformat()
        data.update(self.getExistingVersionHistories())
        for name, utilClass in getUtilitiesFor(ICallHomeCollector):
            try:
                chData = utilClass().generateData()
                if chData:
                    if ERROR_KEY in chData:
                        errors.extend(chData[ERROR_KEY])
                        del chData[ERROR_KEY]
                    data.update(chData)
            except Exception, e:
                errorObject = dict(callhome_collector=utilClass.__name__,
                                   name=name,
                                   exception=str(e))
                log.warn(("Caught exception while generating callhome data "
                          "%(callhome_collector)s:%(name)s : %(exception)s") %
                         errorObject)
                errors.append(errorObject)
        if self._master:
            for name, utilClass in getUtilitiesFor(IMasterCallHomeCollector):
                try:
                    chData = utilClass().generateData(self._dmd)
                    if chData:
                        if ERROR_KEY in chData:
                            errors.extend(chData[ERROR_KEY])
                            del chData[ERROR_KEY]
                        data.update(chData)
                except Exception, e:
                    errorObject = dict(callhome_collector=utilClass.__name__,
                                       name=name,
                                       exception=str(e))
                    log.warn(("Caught exception while generating callhome "
                              "data %(callhome_collector)s:%(name)s : "
                              "%(exception)s") % errorObject)
                    errors.append(errorObject)
Beispiel #42
0
 def __call__(self, context):
     terms = []
     extenders = [
         a[0] for a in getUtilitiesFor(ICatalogFactory)
         if a[0].startswith('user_properties') and a[0] != 'user_properties'
     ]
     for extender in extenders:
         terms.append(
             SimpleVocabulary.createTerm(extender, str(extender), extender))
     return SimpleVocabulary(terms)
def FieldsVocabularyFactory(context=None):
    request = getRequest()
    terms = []
    for (field_id, factory) in getUtilitiesFor(IFieldFactory):
        terms.append(
            SimpleVocabulary.createTerm(
                field_id, factory.title,
                translate(factory.title, context=request)))
    terms = sorted(terms, key=operator.attrgetter('title'))
    return SimpleVocabulary(terms)
def setupVarious_uninstall(context):
    # We must remove the manager interface from all portlets where it has been added.
    # If we miss to do this, the product could never be removed from the instance.
    portlets = getUtilitiesFor(IPortletType)
    for name, portlet_type in portlets:
        # if it has our interface: remove it
        if IPersonalPortletManager in portlet_type.for_:
            portlet_type.for_.remove(IPersonalPortletManager)
            # IMPORTANT to make this dirty for ZODB
            portlet_type.for_ = portlet_type.for_
 def _addable_portlet_types(self):
     # in the original class, we had:
     #      portlets = self.manager.getAddablePortletTypes()
     # ... we would get the portlets registered for IPersonalPortletManager.
     # Instead, we query the ones registered for IColumn, in a hardcoded way.
     # 
     manager_interface = IColumn
     portlet_types = [ p for (_name, p) in getUtilitiesFor(IPortletType) 
                       if manager_interface in p.for_ ]
     return portlet_types
    def setUp(self):
        self.portal = self.layer['portal']
        self.request = self.layer['request']
        alsoProvides(self.request, ISocialLikeLayer)
        self.plugins = dict(getUtilitiesFor(IPlugin))
        self.plugin = self.plugins[name]

        with api.env.adopt_roles(['Manager']):
            self.document = api.content.create(
                self.portal, 'Document', 'my-document')
Beispiel #47
0
 def _getOptionsFilter(self, options):
     deviceFilter = lambda x: True
     if options:
         dispatchFilterName = options.get('configDispatch', '') if options else ''
         filterFactories = dict(component.getUtilitiesFor(IConfigurationDispatchingFilter))
         filterFactory = filterFactories.get(dispatchFilterName, None) or \
                         filterFactories.get('', None)
         if filterFactory:
             deviceFilter = filterFactory.getFilter(options) or deviceFilter
     return deviceFilter
def DisplayTypeVocabulary(context):
    terms = []
    utils = list(getUtilitiesFor(IDisplayType))
    for name, utility in sorted(utils, key=lambda x: x[1].name):
        if utility.name:
            name = utility.name or name
            terms.append(SimpleTerm(name, name, utility.description))

    return PTGVocabulary(terms,
                         default=IGallerySettings['display_type'].default)
Beispiel #49
0
def getDefaultSettings():
    settings = {}
    for name, description in IPersonalPreferences.namesAndDescriptions():
        settings[name] = description.default
    utilities = component.getUtilitiesFor(ISettings)
    for name, utility in utilities:
        interface = utility.getInterface()
        for name, description in interface.namesAndDescriptions():
            settings[name] = description.default
    return settings
def ValidatorsVocabularyFactory(context):
    """Field validators vocabulary"""
    from collective.easyform.interfaces import IFieldValidator

    return SimpleVocabulary(
        [
            SimpleVocabulary.createTerm(i, i, i)
            for i, u in getUtilitiesFor(IFieldValidator)
        ]
    )
Beispiel #51
0
    def guessUtility(self, columnType=''):
        """ Get guess utility from columnType
        """
        if not columnType:
            return None, None

        for name, util in getUtilitiesFor(IGuessType):
            if columnType in util.aliases:
                return name, util
        return None, None
 def get_delivery_services(self):
     result = atapi.DisplayList()
     result.add(
         u'mailhost',
         _(u'EasyNewsletter_label_PloneMailHost',
           u'Default Plone Mailhost'))
     for utility in getUtilitiesFor(IMailHost):
         if utility[0]:
             result.add(utility[0], utility[0])
     return result
Beispiel #53
0
    def setUp(self):
        self.portal = self.layer['portal']
        setRoles(self.portal, TEST_USER_ID, ['Manager'])
        self.setup_content(self.portal)

        self.registry = getUtility(IRegistry)
        self.settings = self.registry.forInterface(ISocialLikeSettings)

        self.plugins = dict(getUtilitiesFor(IPlugin))
        self.plugin = self.plugins[name]
Beispiel #54
0
 def __call__(self, context):
     # Get all portlets, for all portlet manager interfaces.
     portlets = [
         schema.vocabulary.SimpleVocabulary.createTerm(
             portlet.addview,  # value
             portlet.addview,  # token
             api.portal.translate(portlet.title)  # title
         ) for (name, portlet) in getUtilitiesFor(IPortletType)
     ]
     return schema.vocabulary.SimpleVocabulary(portlets)
Beispiel #55
0
def bootstrap_evolution(root):
    from zope.component import getUtilitiesFor
    from repoze.evolution import IEvolutionManager
    for pkg_name, factory in getUtilitiesFor(IEvolutionManager):
        __import__(pkg_name)
        package = sys.modules[pkg_name]
        manager = factory(root, pkg_name, package.VERSION)
        # when we do start_over, we unconditionally set the database's
        # version number to the current code number
        manager._set_db_version(package.VERSION)
Beispiel #56
0
 def __init__(self, *args, **kwargs):
     super(PageTemplate, self).__init__(*args, **kwargs)
     self.engines = {}
     for engine_iface in (ITextTemplateEngine, IXMLTemplateEngine,
                          IHTMLTemplateEngine, ITemplateEngine):
         engine_type = engine_iface.getTaggedValue('engine_type')
         for name, engine in component.getUtilitiesFor(engine_iface):
             self.engines[(name, engine_type)] = engine
     if not self.engines:  # pragma: no cover
         logger.warning("No configured template engines found.")
Beispiel #57
0
 def update(self):
     active = self.request.getURL().split('/')[-1].split(
         '@@')[-1] == 'config'
     site_url = absoluteURL(hooks.getSite(), self.request)
     self.menu = []
     for name, _ in getUtilitiesFor(IPersistentConfigType):
         self.menu.append(
             u'<a class="action %s" href="%s/++etc++site/config?type=%s">%s</a>'
             % (active and self.request.get('type') == name and 'active'
                or '', site_url, cgi.escape(name), name))
 def findPortlet(self):
     portlet_path = self.request.form.get('path')
     portlet_name = self.request.form.get('portlet')
     portlet_context = self.context.restrictedTraverse(portlet_path)
     for manager_name, src_manager in getUtilitiesFor(IPortletManager, context=portlet_context):
         src_manager_assignments = getMultiAdapter((portlet_context, src_manager), IPortletAssignmentMapping)
         portlet_assignments = src_manager_assignments.get(portlet_name)
         if portlet_assignments:
             break
     return portlet_assignments
Beispiel #59
0
def PermissionsVocabulary(context=None):
    """
    A vocabulary of permission IDs.

    Term values are permissions, while term tokens are permission IDs.
    """
    terms = []
    for name, permission in getUtilitiesFor(IPermission, context):
        terms.append(SimpleTerm(permission, name))
    return SimpleVocabulary(terms)
Beispiel #60
0
def setup_z2_roles(context):
    if context.readDataFile("marker.txt") is None:
        return
    portal = context.getSite()
    roles = list(portal.__ac_roles__)
    for name, role in component.getUtilitiesFor(IRole):
        if name not in roles:
            roles.append(name)
    roles.sort()
    portal.__ac_roles__ = tuple(roles)