def setUp(self):
        from Products.CMFCore.CatalogTool import CatalogTool
        from Products.CMFCore.utils import registerToolInterface
        from Products.CMFUid.interfaces import IUniqueIdHandler
        from Products.CMFUid.UniqueIdAnnotationTool \
            import UniqueIdAnnotationTool
        from Products.CMFUid.UniqueIdGeneratorTool \
            import UniqueIdGeneratorTool

        SecurityTest.setUp(self)
        self.app._setObject('dummy', DummyContent(id='dummy'))
        self.app._setObject('dummy2', DummyContent(id='dummy2'))
        self.ctool = CatalogTool().__of__(self.app)
        self.uidhandler = self._makeOne()
        sm = getSiteManager()
        sm.registerUtility(self.ctool, ICatalogTool)
        registerToolInterface('portal_catalog', ICatalogTool)
        sm.registerUtility(self.uidhandler, IUniqueIdHandler)
        sm.registerUtility(UniqueIdAnnotationTool(),
                           IUniqueIdAnnotationManagement)
        sm.registerUtility(UniqueIdGeneratorTool(), IUniqueIdGenerator)
        sm.registerUtility(provided=IPortalCatalogQueueProcessor, factory=PortalCatalogProcessor)

        # Make sure we have our indices/columns
        uid_name = self.uidhandler.UID_ATTRIBUTE_NAME
        self.ctool.addIndex(uid_name, 'FieldIndex')
        self.ctool.addColumn(uid_name)
    def setUp(self):
        from Products.CMFUid.interfaces import IUniqueIdAnnotationManagement
        from Products.CMFCore.utils import registerToolInterface

        SecurityTest.setUp(self)
        self.uidannotation = self._makeOne()
        registerToolInterface('portal_uidhandler', IUniqueIdHandler)

        sm = getSiteManager()
        sm.registerUtility(self.uidannotation, IUniqueIdAnnotationManagement)
        sm.registerUtility(DummyUniqueIdHandlerTool(), IUniqueIdHandler)

        self.app._setObject('dummy', DummyContent(id='dummy'))
        self.app._setObject('site', Folder('site'))

        transaction.savepoint(optimistic=True)
Exemplo n.º 3
0
    #
    security.declarePrivate('ZCacheManager_getCache')
    def ZCacheManager_getCache(self):
        """ Retrieve a cache object
        """
        cache = getattr(self, '_cache', None)

        if cache is None:
            self._cache = CPMCache()
            cache = self._cache

        return cache


InitializeClass( CachingPolicyManager )
registerToolInterface('caching_policy_manager', ICachingPolicyManager)


def handleCachingPolicyManagerEvent(ob, event):
    """ Event subscriber for (un)registering a CPM as CacheManager
    """
    if not ICachingPolicyManager.providedBy(ob):
        return

    if IObjectMovedEvent.providedBy(event):
        if event.newParent is not None:
            ids = getVerifiedManagerIds(event.newParent)
            id = ob.getId()
            if id not in ids:
                setattr(event.newParent, ZCM_MANAGERS, ids + (id,))
        try:
            registration.addMember(user_id, password, REQUEST=request)
        except (AttributeError, ValueError), err:
            logging.exception(err)
            IStatusMessage(request).addStatusMessage(err, type="error")
            return

        # set additional properties using the user schema adapter
        schema = getUtility(IUserDataSchemaProvider).getSchema()

        adapter = getAdapter(portal, schema)
        adapter.context = mt.getMemberById(user_id)

        for name in getFieldNamesInOrder(schema):
            if name in data:
                setattr(adapter, name, data[name])

        notify(UserApprovedEvent(data)) 
        del self._data[key]


    def reject(self, key):
        if key not in self._data.keys():
            return
        data = self._data[key]
        notify(UserRejectedEvent(data))
        del self._data[key]

InitializeClass(RegistrationApproval)
registerToolInterface('wcc_membership_registration_approval', IRegistrationApproval)
Exemplo n.º 5
0
def initialize(context):
    from Products.CMFCore.utils import ToolInit
    from Products.CMFCore.utils import ContentInit
    from Products.CMFCore.utils import registerIcon
    from Products.CMFDefault.permissions import AddPortalContent

    import DefaultWorkflow
    import DiscussionTool
    import Document
    import factory
    import Favorite
    import File
    import Image
    import Link
    import MembershipTool
    import MetadataTool
    import NewsItem
    import Portal
    import PropertiesTool
    import RegistrationTool
    import SkinnedFolder
    import SyndicationTool

    # Make sure security is initialized
    import DiscussionItem
    import DublinCore
    import utils

    contentConstructors = ( Document.addDocument
                        , File.addFile
                        , Image.addImage
                        , Link.addLink
                        , Favorite.addFavorite
                        , NewsItem.addNewsItem
                        , SkinnedFolder.addSkinnedFolder
                        )

    tools = ( DiscussionTool.DiscussionTool
            , MembershipTool.MembershipTool
            , RegistrationTool.RegistrationTool
            , PropertiesTool.PropertiesTool
            , MetadataTool.MetadataTool
            , SyndicationTool.SyndicationTool
            )

    # Register the ID to interface data for those items that don't have their 
    # own module
    from Products.CMFCore.utils import registerToolInterface
    from Products.GenericSetup.interfaces import ISetupTool
    registerToolInterface('portal_setup', ISetupTool)
    from Products.MailHost.interfaces import IMailHost
    registerToolInterface('MailHost', IMailHost)

    ToolInit( 'CMF Default Tool'
            , tools=tools
            , icon='tool.gif'
            ).initialize( context )

    # BBB: register oldstyle constructors
    ContentInit( 'CMF Default Content'
               , content_types=()
               , permission=AddPortalContent
               , extra_constructors=contentConstructors
               , visibility=None
               ).initialize( context )

    context.registerClass( Portal.CMFSite
                         , constructors=(factory.addConfiguredSiteForm,
                                         factory.addConfiguredSite)
                         , icon='images/portal.gif'
                         )

    registerIcon( DefaultWorkflow.DefaultWorkflowDefinition
                , 'images/workflow.gif'
                , globals()
                )

    # make registerHelp work with 2 directories
    help = context.getProductHelp()
    lastRegistered = help.lastRegistered
    context.registerHelp(directory='help', clear=1)
    context.registerHelp(directory='interfaces', clear=1)
    if help.lastRegistered != lastRegistered:
        help.lastRegistered = None
        context.registerHelp(directory='help', clear=1)
        help.lastRegistered = None
        context.registerHelp(directory='interfaces', clear=0)
    context.registerHelpTitle('CMF Default Help')
Exemplo n.º 6
0
            a1['action'] = a.getActionExpression()
            a1['condition'] = a.getCondition()
            a1['appId'] = a.getAppId()
            a1['description'] = a.getDescription()
            a1['icon_expr'] = a.getIconExpression()
            actions.append(a1)

        # possible_permissions is in OFS.role.RoleManager.
        pp = self.possible_permissions()
        return self._actions_form(
            self,
            REQUEST,
            actions=actions,
            possible_permissions=pp,
            management_view='Actions',
            manage_tabs_message=manage_tabs_message,
        )

    @property
    def site_url(self):
        """Return the absolute URL to the current site, which is likely not
        necessarily the portal root.
        Used by ``portlet_prefs`` to construct the URL to
        ``@@overview-controlpanel``.
        """
        return getSite().absolute_url()


InitializeClass(PloneControlPanel)
registerToolInterface('portal_controlpanel', IControlPanel)
Exemplo n.º 7
0
        , MembershipTool.MembershipTool
        , RegistrationTool.RegistrationTool
        , PropertiesTool.PropertiesTool
        , MetadataTool.MetadataTool
        , SyndicationTool.SyndicationTool
        )

# Make the skins available as DirectoryViews.
registerDirectory('skins', globals())
registerDirectory('help', globals())

# Register the ID to interface data for those items that don't have their 
# own module
from Products.CMFCore.utils import registerToolInterface
from Products.GenericSetup.interfaces import ISetupTool
registerToolInterface('portal_setup', ISetupTool)
from Products.MailHost.interfaces import IMailHost
registerToolInterface('MailHost', IMailHost)

def initialize(context):

    ToolInit( 'CMF Default Tool'
            , tools=tools
            , icon='tool.gif'
            ).initialize( context )

    # BBB: register oldstyle constructors
    ContentInit( 'CMF Default Content'
               , content_types=()
               , permission=AddPortalContent
               , extra_constructors=contentConstructors
Exemplo n.º 8
0
        """Remove from catalog.
        """
        url = self.__url(object)
        self.uncatalog_object(url)

    security.declarePrivate('reindexObject')

    def reindexObject(self, object, idxs=[], update_metadata=1, uid=None):
        """Update catalog after object data has changed.

        The optional idxs argument is a list of specific indexes
        to update (all of them by default).

        The update_metadata flag controls whether the object's
        metadata record is updated as well.

        If a non-None uid is passed, it will be used as the catalog uid
        for the object instead of its physical path.
        """
        if uid is None:
            uid = self.__url(object)
        if idxs != []:
            # Filter out invalid indexes.
            valid_indexes = self._catalog.indexes.keys()
            idxs = [i for i in idxs if i in valid_indexes]
        self.catalog_object(object, uid, idxs, update_metadata)


InitializeClass(CatalogTool)
registerToolInterface('portal_catalog', ICatalogTool)
Exemplo n.º 9
0
        settings = registry.forInterface(ISiteSyndicationSettings)
        return settings.allowed

    def isSyndicationAllowed(self, obj=None):
        """
        Check whether syndication is enabled for the site.  This
        provides for extending the method to check for whether a
        particular obj is enabled, allowing for turning on only
        specific folders for syndication.
        """
        settings = IFeedSettings(obj)
        return settings.enabled

    def enableSyndication(self, obj):
        """
        Enable syndication for the obj
        """
        if not _checkPermission(ModifyPortalContent, obj):
            raise Unauthorized
        settings = IFeedSettings(obj)
        settings.enabled = True

    def disableSyndication(self, obj):
        if not _checkPermission(ModifyPortalContent, obj):
            raise Unauthorized
        settings = IFeedSettings(obj)
        settings.enabled = False


registerToolInterface('portal_syndication', ISyndicationTool)
    def findTypeName(self, name, typ, body):
        """
            Perform a lookup over a collection of rules, returning the
            the name of the Type object corresponding to name/typ/body.
            Return None if no match found.
        """
        for predicate_id in self.predicate_ids:
            pred, typeObjectName = self.predicates[predicate_id]
            if pred(name, typ, body):
                return typeObjectName

        return None


InitializeClass(ContentTypeRegistry)
registerToolInterface('content_type_registry', IContentTypeRegistry)


def manage_addRegistry(self, REQUEST=None):
    """
        Add a CTR to self.
    """
    CTRID = ContentTypeRegistry.id
    reg = ContentTypeRegistry()
    self._setObject(CTRID, reg)
    reg = self._getOb(CTRID)

    if REQUEST is not None:
        REQUEST['RESPONSE'].redirect(self.absolute_url() + '/manage_main' +
                                     '?manage_tabs_message=Registry+added.')
Exemplo n.º 11
0
def initialize(context):
    from Products.CMFCore.utils import ToolInit
    from Products.CMFCore.utils import ContentInit
    from Products.CMFCore.utils import registerIcon
    from Products.CMFDefault.permissions import AddPortalContent

    import DefaultWorkflow
    import DiscussionTool
    import Document
    import factory
    import Favorite
    import File
    import Image
    import Link
    import MembershipTool
    import MetadataTool
    import NewsItem
    import Portal
    import PropertiesTool
    import RegistrationTool
    import SkinnedFolder
    import SyndicationTool

    # Make sure security is initialized
    import DiscussionItem
    import DublinCore
    import utils

    contentConstructors = (Document.addDocument, File.addFile, Image.addImage,
                           Link.addLink, Favorite.addFavorite,
                           NewsItem.addNewsItem,
                           SkinnedFolder.addSkinnedFolder)

    tools = (DiscussionTool.DiscussionTool, MembershipTool.MembershipTool,
             RegistrationTool.RegistrationTool, PropertiesTool.PropertiesTool,
             MetadataTool.MetadataTool, SyndicationTool.SyndicationTool)

    # Register the ID to interface data for those items that don't have their
    # own module
    from Products.CMFCore.utils import registerToolInterface
    from Products.GenericSetup.interfaces import ISetupTool
    registerToolInterface('portal_setup', ISetupTool)
    from Products.MailHost.interfaces import IMailHost
    registerToolInterface('MailHost', IMailHost)

    ToolInit('CMF Default Tool', tools=tools,
             icon='tool.gif').initialize(context)

    # BBB: register oldstyle constructors
    ContentInit('CMF Default Content',
                content_types=(),
                permission=AddPortalContent,
                extra_constructors=contentConstructors,
                visibility=None).initialize(context)

    context.registerClass(Portal.CMFSite,
                          constructors=(factory.addConfiguredSiteForm,
                                        factory.addConfiguredSite),
                          icon='images/portal.gif')

    registerIcon(DefaultWorkflow.DefaultWorkflowDefinition,
                 'images/workflow.gif', globals())

    # make registerHelp work with 2 directories
    help = context.getProductHelp()
    lastRegistered = help.lastRegistered
    context.registerHelp(directory='help', clear=1)
    context.registerHelp(directory='interfaces', clear=1)
    if help.lastRegistered != lastRegistered:
        help.lastRegistered = None
        context.registerHelp(directory='help', clear=1)
        help.lastRegistered = None
        context.registerHelp(directory='interfaces', clear=0)
    context.registerHelpTitle('CMF Default Help')

def _makeWorkflowPolicyFactoryKey(factory, id=None, title=None):
    # The factory should take one argument, id.
    if id is None:
        id = getattr(factory, 'id', '') or getattr(factory, 'meta_type', '')
    if title is None:
        title = getattr(factory, 'title', '')
    key = id
    if title:
        key = key + ' (%s)' % title
    return key


def addWorkflowPolicyFactory(factory, id=None, title=None):
    key = _makeWorkflowPolicyFactoryKey(factory, id, title)
    _workflow_policy_factories[key] = factory


def _removeWorkflowPolicyFactory(factory, id=None, title=None):
    """ Make teardown in unitcase cleaner. """
    key = _makeWorkflowPolicyFactoryKey(factory, id, title)
    try:
        del _workflow_policy_factories[key]
    except KeyError:
        pass


InitializeClass(PlacefulWorkflowTool)
registerToolInterface('portal_placeful_workflow', IPlacefulWorkflowTool)
    @security.protected(AddPortalMember)
    def isMemberIdAllowed(self, id):
        '''Returns 1 if the ID is not in use and is not reserved.
        '''
        if len(id) < 1 or id == 'Anonymous User':
            return 0
        if not self._ALLOWED_MEMBER_ID_PATTERN.match(id):
            return 0
        mtool = getUtility(IMembershipTool)
        if mtool.getMemberById(id) is not None:
            return 0
        return 1

    security.declarePublic('afterAdd')

    def afterAdd(self, member, id, password, properties):
        '''Called by portal_registration.addMember()
        after a member has been added successfully.'''
        pass

    @security.protected(MailForgottenPassword)
    def mailPassword(self, forgotten_userid, REQUEST):
        '''Email a forgotten password to a member.  Raises an exception
        if user ID is not found.
        '''
        raise NotImplementedError


InitializeClass(RegistrationTool)
registerToolInterface('portal_registration', IRegistrationTool)
Exemplo n.º 14
0
    def createChangeSet(self, ob1, ob2, id1=None, id2=None):
        """Returns a ChangeSet object that represents the differences
        between ob1 and ob2 (ie. ob2 - ob1) ."""
        # FIXME: Pick a better ID
        cs = BaseChangeSet('Changes').__of__(self)
        cs.computeDiff(ob1, ob2, id1=id1, id2=id2)
        return aq_base(cs)


def registerDiffType(klass):
    """Register a class for computing differences.

    Instances of the class must implement the IDifference
    interface."""

    CMFDiffTool._difftypes[klass.meta_type] = klass


def unregisterDiffType(klass):
    """Register a class for computing differences.

    Instances of the class must implement the IDifference
    interface."""

    del CMFDiffTool._difftypes[klass.meta_type]


InitializeClass(CMFDiffTool)
registerToolInterface('portal_diff', IDiffTool)
Exemplo n.º 15
0
 </object>
</object>
"""

_REMOVE_IMPORT = """\
<?xml version="1.0"?>
<object name="portal_actions">
 <action-provider name="portal_actions" remove=""/>
 <action-provider name="not_existing" remove=""/>
 <action-provider name="portal_bar" remove=""/>
</object>
"""

class IFoo(Interface):
    """ Foo interface """
registerToolInterface('portal_foo', IFoo)

class IBar(Interface):
    """ Bar interface """
registerToolInterface('portal_bar', IBar)


class DummyTool(OrderedFolder, ActionProviderBase):

    __implements__ = IActionProvider


class DummyUser(Implicit):

    def getId(self):
        return 'dummy'
Exemplo n.º 16
0
from Products.PluggableAuthService.interfaces.authservice import \
    IPluggableAuthService
from Products.PluggableAuthService.interfaces.plugins import \
    IAuthenticationPlugin
from Products.PluggableAuthService.interfaces.plugins import \
    IGroupEnumerationPlugin
from Products.PluggableAuthService.interfaces.plugins import \
    IRoleAssignerPlugin
from Products.PluggableAuthService.interfaces.plugins import \
    IUserEnumerationPlugin
from zope.event import notify
import logging

logger = logging.getLogger('PlonePAS')

registerToolInterface('acl_users', IPluggableAuthService)

#################################
# helper functions


def _userSetGroups(pas, user_id, groupnames):
    """method was used at GRUF level, but is used inside this monkies at several
    places too.

    We no longer provide it on PAS to clean up patches

    """
    plugins = pas.plugins
    gtool = getToolByName(pas, "portal_groups")
Exemplo n.º 17
0
                )
        return transactions

    security.declarePublic('undo')
    def undo(self, object, transaction_info):
        """
            Undo the list of transactions passed in 'transaction_info',
            first verifying that the current user is allowed to undo them.
        """
        # Belt and suspenders:  make sure that the user is actually
        # allowed to undo the transation(s) in transaction_info.

        xids = {}  # set of allowed transaction IDs

        allowed = self.listUndoableTransactionsFor( object )

        for xid in map( lambda x: x['id'], allowed ):
            xids[xid] = 1

        if type( transaction_info ) == type( '' ):
            transaction_info = [ transaction_info ]

        for tinfo in transaction_info:
            if not xids.get( tinfo, None ):
                raise AccessControl_Unauthorized

        object.manage_undo_transactions(transaction_info)

InitializeClass(UndoTool)
registerToolInterface('portal_undo', IUndoTool)
            a1['action'] = a.getActionExpression()
            a1['condition'] = a.getCondition()
            a1['appId'] = a.getAppId()
            a1['description'] = a.getDescription()
            a1['icon_expr'] = a.getIconExpression()
            actions.append(a1)

        # possible_permissions is in OFS.role.RoleManager.
        pp = self.possible_permissions()
        return self._actions_form(
            self,
            REQUEST,
            actions=actions,
            possible_permissions=pp,
            management_view='Actions',
            manage_tabs_message=manage_tabs_message,
        )

    @property
    def site_url(self):
        """Return the absolute URL to the current site, which is likely not
        necessarily the portal root.
        Used by ``portlet_prefs`` to construct the URL to
        ``@@overview-controlpanel``.
        """
        return getSite().absolute_url()


InitializeClass(PloneControlPanel)
registerToolInterface('portal_controlpanel', IControlPanel)
Exemplo n.º 19
0
from OFS.SimpleItem import SimpleItem
from Products.CMFCore.utils import registerToolInterface
from zope.interface import Interface


MetadataTool = SimpleItem


class FactoryTool(SimpleItem):
    ''' Compatibility code for portal_factory
    '''

    def __nonzero__(self):
        ''' Always evealuate to False
        '''
        return 0


class IFactoryTool(Interface):
    pass
registerToolInterface('portal_factory', IFactoryTool)
        try:
            registration.addMember(user_id, password, REQUEST=request)
        except (AttributeError, ValueError), err:
            logging.exception(err)
            IStatusMessage(request).addStatusMessage(err, type="error")
            return

        # set additional properties using the user schema adapter
        schema = getUtility(IUserDataSchemaProvider).getSchema()

        adapter = getAdapter(portal, schema)
        adapter.context = mt.getMemberById(user_id)

        for name in getFieldNamesInOrder(schema):
            if name in data:
                setattr(adapter, name, data[name])

        notify(UserApprovedEvent(data)) 
        del self._data[key]


    def reject(self, key):
        if key not in self._data.keys():
            return
        data = self._data[key]
        notify(UserRejectedEvent(data))
        del self._data[key]

InitializeClass(RegistrationApproval)
registerToolInterface('portal_registration_approval', IRegistrationApproval)
Exemplo n.º 21
0
    security = ClassSecurityInfo()

    security.declarePrivate('__init__')
    def __init__(self):
        """Initialize the generator
        """
        # The previous ``BTrees.Length.Length`` implementation may cause 
        # double unique ids under high load. So for the moment we just use 
        # a simple counter.
        self._uid_counter = 0

    security.declarePrivate('__call__')
    def __call__(self):
        """See IUniqueIdGenerator.
        """
        # For sites that have already used CMF 1.5.1 (and older) the
        # BTrees.Length.Length object has to be migrated to an integer.
        if isinstance(self._uid_counter, Length):
            self._uid_counter = self._uid_counter()
        self._uid_counter += 1
        return self._uid_counter

    security.declarePrivate('convert')
    def convert(self, uid):
        """See IUniqueIdGenerator.
        """
        return int(uid)

InitializeClass(UniqueIdGeneratorTool)
registerToolInterface('portal_uidgenerator', IUniqueIdGenerator)
Exemplo n.º 22
0
        if test:
            self.testSkinPath(skinpath)
        sels[str(skinname)] = skinpath
        if make_default:
            self.default_skin = skinname

    @security.protected(AccessContentsInformation)
    def getDiff(self, item_one_path, item_two_path, reverse=0):
        """ Return a diff between one and two.
        """
        if not reverse:
            item_one = self.unrestrictedTraverse(item_one_path)
            item_two = self.unrestrictedTraverse(item_two_path)
        else:
            item_one = self.unrestrictedTraverse(item_two_path)
            item_two = self.unrestrictedTraverse(item_one_path)

        res = unified_diff(item_one.read().splitlines(),
                           item_two.read().splitlines(),
                           item_one_path,
                           item_two_path,
                           '',
                           '',
                           lineterm="")
        return res


InitializeClass(SkinsTool)
registerToolInterface('portal_skins', ISkinsTool)
Exemplo n.º 23
0
        # the user as context.
        return portal_group.__of__(self).__of__(g)

    security.declarePrivate('registerGroupData')
    def registerGroupData(self, g, id):
        '''
        Adds the given member data to the _members dict.
        This is done as late as possible to avoid side effect
        transactions and to reduce the necessary number of
        entries.
        '''
        self._members[id] = aq_base(g)


InitializeClass(GroupDataTool)
registerToolInterface('portal_groupdata', IGroupDataTool)


class GroupData(SimpleItem):

    implements(IGroupData, IManageCapabilities)

    security = ClassSecurityInfo()

    id = None
    _tool = None

    def __init__(self, tool, id):
        self.id = id
        # Make a temporary reference to the tool.
        # The reference will be removed by notifyModified().
Exemplo n.º 24
0
        {
            'id': 'remove_on_clone',
            'type': 'boolean',
            'mode': 'w',
            'label': 'Remove the objects unique id on clone (CAUTION !!!)'
        },
        {
            'id': 'assign_on_add',
            'type': 'boolean',
            'mode': 'w',
            'label': "Assign a unique ID when an object is added"
        },
        {
            'id': 'assign_on_clone',
            'type': 'boolean',
            'mode': 'w',
            'label': "Assign a unique ID when an object is cloned"
        },
    )

    security.declarePrivate('__call__')

    def __call__(self, obj, id):
        """See IUniqueIdAnnotationManagement.
        """
        return UniqueIdAnnotation(obj, id)


InitializeClass(UniqueIdAnnotationTool)
registerToolInterface('portal_uidannotation', IUniqueIdAnnotationManagement)
Exemplo n.º 25
0
                        self.portal_workflow.updateRoleMappings()
                        self._needUpdateRole = 0
                    except (ConflictError, KeyboardInterrupt):
                        raise
                    except:
                        logger.error("Exception was thrown while updating "
                                     "role mappings", exc_info=True)
                        if not swallow_errors:
                            raise
                logger.info("Your Plone instance is now up-to-date.")

            if dry_run:
                logger.info("Dry run selected, transaction aborted")
                transaction.abort()

            return stream.getvalue()

        finally:
            logger.removeHandler(handler)
            gslogger.removeHandler(handler)

    upgrade = postonly(upgrade)


def registerUpgradePath(oldversion, newversion, function):
    """ Basic register func """
    pass

InitializeClass(MigrationTool)
registerToolInterface('portal_migration', IMigrationTool)
Exemplo n.º 26
0
    def __init__(self):
        """Initialize the generator
        """
        # The previous ``BTrees.Length.Length`` implementation may cause
        # double unique ids under high load. So for the moment we just use
        # a simple counter.
        self._uid_counter = 0

    security.declarePrivate('__call__')

    def __call__(self):
        """See IUniqueIdGenerator.
        """
        # For sites that have already used CMF 1.5.1 (and older) the
        # BTrees.Length.Length object has to be migrated to an integer.
        if isinstance(self._uid_counter, Length):
            self._uid_counter = self._uid_counter()
        self._uid_counter += 1
        return self._uid_counter

    security.declarePrivate('convert')

    def convert(self, uid):
        """See IUniqueIdGenerator.
        """
        return int(uid)


InitializeClass(UniqueIdGeneratorTool)
registerToolInterface('portal_uidgenerator', IUniqueIdGenerator)
Exemplo n.º 27
0
    id = 'portal_uidannotation'
    alternative_id = "portal_standard_uidannotation"
    meta_type = 'Unique Id Annotation Tool'

    security = ClassSecurityInfo()

    remove_on_add = True
    remove_on_clone = True
    assign_on_add = False
    assign_on_clone = False
    _properties = (
    {'id': 'remove_on_add', 'type': 'boolean', 'mode': 'w',
     'label': "Remove the objects unique id on add (and import)"},
    {'id': 'remove_on_clone', 'type': 'boolean', 'mode': 'w',
     'label': 'Remove the objects unique id on clone (CAUTION !!!)'},
    {'id': 'assign_on_add', 'type': 'boolean', 'mode': 'w',
     'label': "Assign a unique ID when an object is added"},
    {'id': 'assign_on_clone', 'type': 'boolean', 'mode': 'w',
     'label': "Assign a unique ID when an object is cloned"},
    )

    security.declarePrivate('__call__')
    def __call__(self, obj, id):
        """See IUniqueIdAnnotationManagement.
        """
        return UniqueIdAnnotation(obj, id)

InitializeClass(UniqueIdAnnotationTool)
registerToolInterface('portal_uidannotation', IUniqueIdAnnotationManagement)
Exemplo n.º 28
0
        """
        if id is None:
            member = self.getAuthenticatedMember()
            if not hasattr(member, 'getMemberId'):
                return None
            id = member.getMemberId()
        members = self.getMembersFolder()
        if members:
            try:
                folder = members._getOb(id)
                if verifyPermission and not _checkPermission(View, folder):
                    # Don't return the folder if the user can't get to it.
                    return None
                return folder
            except (AttributeError, TypeError, KeyError):
                pass
        return None

    def getHomeUrl(self, id=None, verifyPermission=0):
        """ Return the URL to a member's home folder, or None.
        """
        home = self.getHomeFolder(id, verifyPermission)
        if home is not None:
            return home.absolute_url()
        else:
            return None

InitializeClass(MembershipTool)
registerToolInterface('portal_membership', IMembershipTool)

Exemplo n.º 29
0
    security.declareProtected(ManagePortal, 'upgradeProduct')

    def upgradeProduct(self, pid):
        profile = self.getInstallProfile(pid)
        if profile is None:
            # No upgrade profiles
            return self.reinstallProducts(products=[pid])
        profile_id = profile['id']
        setup = getToolByName(self, 'portal_setup')
        upgrades = setup.listUpgrades(profile_id)
        for upgrade in upgrades:
            # An upgrade may be a single step (for a bare upgradeStep)
            # or a list of steps (for upgradeSteps containing upgradeStep
            # directives).
            if not type(upgrade) is list:
                upgrade = [upgrade]
            for upgradestep in upgrade:
                step = upgradestep['step']
                step.doStep(setup)
        version = str(profile['version'])
        if version == 'latest':
            version = self.getLatestUpgradeStep(profile_id)
        setup.setLastVersionForProfile(profile_id, version)


QuickInstallerTool.__doc__ = BaseTool.__doc__

InitializeClass(QuickInstallerTool)
registerToolInterface('portal_quickinstaller', IQuickInstallerTool)
Exemplo n.º 30
0
        """ Get boolean indicating whether discussion is allowed for content.
        """
        if hasattr(aq_base(content), 'allow_discussion'):
            return bool(content.allow_discussion)

        if IDynamicType.providedBy(content):
            # Grabbing type information objects only works for dynamic types
            typeInfo = content.getTypeInfo()
            if typeInfo:
                return bool(typeInfo.allowDiscussion())

        return False

    #
    #   Utility methods
    #
    security.declarePrivate('_createDiscussionFor')

    def _createDiscussionFor(self, content):
        """ Create DiscussionItemContainer for content, if allowed.
        """
        if not self.isDiscussionAllowedFor(content):
            raise DiscussionNotAllowed

        content.talkback = DiscussionItemContainer()
        return content.talkback


InitializeClass(DiscussionTool)
registerToolInterface('portal_discussion', IDiscussionTool)
Exemplo n.º 31
0
        if portal_obj is None:
            # fallback for bootstrap
            portal_obj = aq_parent(aq_inner(self))
        return portal_obj.__of__(request_container)

    security.declarePublic('getRelativeContentPath')
    def getRelativeContentPath(self, content):
        """ Get the path for an object, relative to the portal root.
        """
        portal_path_length = len( self.getPortalObject().getPhysicalPath() )
        content_path = content.getPhysicalPath()
        return content_path[portal_path_length:]

    security.declarePublic('getRelativeContentURL')
    def getRelativeContentURL(self, content):
        """ Get the URL for an object, relative to the portal root.
        """
        return '/'.join( self.getRelativeContentPath(content) )

    security.declarePublic('getRelativeUrl')
    getRelativeUrl = getRelativeContentURL

    security.declarePublic('getPortalPath')
    def getPortalPath(self):
        """ Get the portal object's URL without the server URL component.
        """
        return '/'.join( self.getPortalObject().getPhysicalPath() )

InitializeClass(URLTool)
registerToolInterface('portal_url', IURLTool)
Exemplo n.º 32
0
        """
        self._members[id] = aq_base(m)

    @security.private
    def deleteMemberData(self, member_id):
        """ Delete member data of specified member.
        """
        members = self._members
        if member_id in members:
            del members[member_id]
            return 1
        else:
            return 0

InitializeClass(MemberDataTool)
registerToolInterface('portal_memberdata', IMemberDataTool)


class MemberData(Persistent):

    def __init__(self, id):
        self.id = id


@implementer(IMember)
class MemberAdapter(object):

    """Member data adapter.
    """

    adapts(IUser, IMemberDataTool)
Exemplo n.º 33
0
                        setter( policy.defaultValue() )
                    elif policy.isRequired():
                        raise MetadataError, \
                            'Metadata element %s is required.' % element

        # TODO:  Call initial_values_hook, if present

    security.declareProtected(View, 'validateMetadata')
    def validateMetadata( self, content ):
        """ See IMetadataTool.
        """
        for schema_id, schema in self.listSchemas():
            for element, policy in schema.listPolicies(
                                    content.getPortalTypeName()):

                value = getattr( content, element )()
                if not value and policy.isRequired():
                    raise MetadataError, \
                            'Metadata element %s is required.' % element

                if value and policy.enforceVocabulary():
                    values = policy.isMultiValued() and value or [ value ]
                    for value in values:
                        if not value in policy.allowedVocabulary():
                            raise MetadataError, \
                            'Value %s is not in allowed vocabulary for ' \
                            'metadata element %s.' % ( value, element )

InitializeClass( MetadataTool )
registerToolInterface('portal_metadata', IMetadataTool)
Exemplo n.º 34
0
Arquivo: atct.py Projeto: dtgit/dtedu
            if not IImageContent.isImplementedBy(obj):
                continue
            try:
                state = obj._p_changed
            except (ConflictError, KeyboardInterrupt):
                raise
            except:
                state = 0

            field = obj.getField('image')
            if field is not None:
                print >> out, 'Updating %s' % obj.absolute_url(1)
                field.removeScales(obj)
                field.createScales(obj)

            if state is None:
                obj._p_deactivate()

        print >> out, "Updated AT Image scales"
        return out.getvalue()

    security.declareProtected(ManagePortal, 'listContentTypes')
    def listContentTypes(self):
        """List all content types. Used for image/folder_types property.
        """
        ttool = getToolByName(self, 'portal_types')
        return ttool.listContentTypes()

InitializeClass(ATCTTool)
registerToolInterface('portal_atct', IATCTTool)
Exemplo n.º 35
0
        if REQUEST:
            REQUEST.RESPONSE.redirect('%s/manage_keys?manage_tabs_message=%s' %
                                      (self.absolute_url(), 'New+key+created.'))

    security.declareProtected(ManagePortal, 'manage_clearAndRegenerate')
    def manage_clearAndRegenerate(self, REQUEST=None):
        """
        Clear all existing keys and create a new keyset.
        """

        self.crypter.clearKeys()

        if REQUEST:
            REQUEST.RESPONSE.redirect('%s/manage_keys?manage_tabs_message=%s' %
                                      (self.absolute_url(), 'All+keys+cleared.'))

    security.declareProtected(ManagePortal, 'manage_clearLogs')
    def manage_clearLogs(self, REQUEST=None):
        """
        create a new key for cryptography
        """

        self.crypter.clearLogs()

        if REQUEST:
            REQUEST.RESPONSE.redirect('%s/manage_keys?manage_tabs_message=%s' %
                                      (self.absolute_url(), 'All+logs+removed.'))

InitializeClass(PloneCryptoTool)
registerToolInterface('leocornus_crypto', IPloneCryptoTool)
Exemplo n.º 36
0
            return when.HTML4()

        syInfo = getattr(obj, 'syndication_information',
                            None)
        if syInfo is not None:
            when = syInfo.syUpdateBase
            return when.HTML4()
        else:
            return 'Syndication is not Allowed'

    def getMaxItems(self, obj=None):
        """
        Return the max_items to be displayed in the syndication
        """
        if not self.isSiteSyndicationAllowed():
            raise 'Syndication is not Allowed'

        if obj is None:
            return self.max_items

        syInfo = getattr(obj, 'syndication_information',
                            None)
        if syInfo is not None:
            return syInfo.max_items
        else:
            return 'Syndication is not Allowed'

InitializeClass(SyndicationTool)
registerToolInterface('portal_syndication', ISyndicationTool)

Exemplo n.º 37
0
        actions = list(oldstyle_actions)

        if object is None and info is not None:
            object = info.object
        if object is not None:
            type_info = self.getTypeInfo(object)
            if type_info is not None:
                actions.extend(type_info.listActions(info, object))

        add_actions = [ti for ti in self.objectValues()
                       if IAction.providedBy(ti)]
        actions.extend(add_actions)

        return actions

    @security.protected(ManagePortal)
    def listMethodAliasKeys(self):
        """ List all defined method alias names.
        """
        _dict = {}
        for ti in self.listTypeInfo():
            aliases = ti.getMethodAliases()
            for k in aliases.keys():
                _dict[k] = 1
        rval = sorted(_dict.keys())
        return rval


InitializeClass(TypesTool)
registerToolInterface('portal_types', ITypesTool)
Exemplo n.º 38
0
        '''
        b = getattr(g, 'aq_base', None)
        if b is None:
            # u isn't wrapped at all.  Wrap it in self.acl_users.
            b = g
            g = g.__of__(self.acl_users)
        if (b is nobody and not wrap_anon) or hasattr(b, 'getMemberId'):
            # This user is either not recognized by acl_users or it is
            # already registered with something that implements the
            # member data tool at least partially.
            return g

        parent = aq_parent(aq_inner(self))
        base = getattr(parent, 'aq_base', None)
        if hasattr(base, 'portal_groupdata'):
            # Get portal_groupdata to do the wrapping.
            gd = getToolByName(parent, 'portal_groupdata')
            try:
                portal_group = gd.wrapGroup(g)
                return portal_group
            except ConflictError:
                raise
            except:
                logger.exception('Error during wrapGroup')
        # Failed.
        return g


InitializeClass(GroupsTool)
registerToolInterface('portal_groups', igroup.IGroupTool)
Exemplo n.º 39
0
                        setter(policy.defaultValue())
                    elif policy.isRequired():
                        raise MetadataError('Metadata element %s is required.'
                                            % element)

        # TODO:  Call initial_values_hook, if present

    security.declareProtected(View, 'validateMetadata')
    def validateMetadata(self, content):
        """ See IMetadataTool.
        """
        for _schema_id, schema in self.listSchemas():
            for element, policy in schema.listPolicies(
                                    content.getPortalTypeName()):

                value = getattr(content, element)()
                if not value and policy.isRequired():
                    raise MetadataError('Metadata element %s is required.'
                                        % element)

                if value and policy.enforceVocabulary():
                    values = policy.isMultiValued() and value or [value]
                    for value in values:
                        if not value in policy.allowedVocabulary():
                            raise MetadataError(
                                'Value %s is not in allowed vocabulary for '
                                'metadata element %s.' % (value, element))

InitializeClass(MetadataTool)
registerToolInterface('portal_metadata', IMetadataTool)
Exemplo n.º 40
0
        b = getattr(g, 'aq_base', None)
        if b is None:
            # u isn't wrapped at all.  Wrap it in self.acl_users.
            b = g
            g = g.__of__(self.acl_users)
        if (b is nobody and not wrap_anon) or hasattr(b, 'getMemberId'):
            # This user is either not recognized by acl_users or it is
            # already registered with something that implements the
            # member data tool at least partially.
            return g

        parent = self.aq_inner.aq_parent
        base = getattr(parent, 'aq_base', None)
        if hasattr(base, 'portal_groupdata'):
            # Get portal_groupdata to do the wrapping.
            gd = getToolByName(parent, 'portal_groupdata')
            try:
                #log("wrapping group %s" % g)
                portal_group = gd.wrapGroup(g)
                return portal_group
            except ConflictError:
                raise
            except:
                logger.exception('Error during wrapGroup')
        # Failed.
        return g


InitializeClass(GroupsTool)
registerToolInterface('portal_groups', igroup.IGroupTool)
Exemplo n.º 41
0
from Products.PluggableAuthService.interfaces.authservice import \
    IPluggableAuthService
from Products.PluggableAuthService.interfaces.plugins import \
    IAuthenticationPlugin
from Products.PluggableAuthService.interfaces.plugins import \
    IGroupEnumerationPlugin
from Products.PluggableAuthService.interfaces.plugins import \
    IRoleAssignerPlugin
from Products.PluggableAuthService.interfaces.plugins import \
    IUserEnumerationPlugin
from zope.event import notify
import logging

logger = logging.getLogger('PlonePAS')

registerToolInterface('acl_users', IPluggableAuthService)


#################################
# helper functions

def _userSetGroups(pas, user_id, groupnames):
    """method was used at GRUF level, but is used inside this monkies at several
    places too.

    We no longer provide it on PAS to clean up patches

    """
    plugins = pas.plugins
    gtool = getToolByName(pas, "portal_groups")
Exemplo n.º 42
0
    #
    @security.private
    def ZCacheManager_getCache(self):
        """ Retrieve a cache object
        """
        cache = getattr(self, '_cache', None)

        if cache is None:
            self._cache = CPMCache()
            cache = self._cache

        return cache


InitializeClass(CachingPolicyManager)
registerToolInterface('caching_policy_manager', ICachingPolicyManager)


def handleCachingPolicyManagerEvent(ob, event):
    """ Event subscriber for (un)registering a CPM as CacheManager
    """
    if not ICachingPolicyManager.providedBy(ob):
        return

    if IObjectMovedEvent.providedBy(event):
        if event.newParent is not None:
            ids = getVerifiedManagerIds(event.newParent)
            id = ob.getId()
            if id not in ids:
                setattr(event.newParent, ZCM_MANAGERS, ids + (id, ))
Exemplo n.º 43
0
    pass


class ITinyMCE(Interface):
    pass


class ICalendarTool(Interface):
    pass


class IActionIconsTool(Interface):
    pass


registerToolInterface('portal_actionicons', IActionIconsTool)


class ActionIcon(SimpleItem):

    _title = None
    _category = 'object'
    _action_id = 'view'
    _icon_expr_text = 'document_icon'

    def __init__(self, category, action_id, icon_expr_text='', title=None):
        self._category = category
        self._action_id = action_id
        self._icon_expr_text = icon_expr_text
        self._title = title
Exemplo n.º 44
0
        # Include actions from specific tools.
        for provider_name in self.listActionProviders():
            provider = getToolByName(self, provider_name)
            if IActionProvider.providedBy(provider):
                actions.extend(provider.listActionInfos(object=object))

        # Include actions from object.
        if object is not None:
            if IActionProvider.providedBy(object):
                actions.extend(object.listActionInfos(object=object))

        # Reorganize the actions by category.
        filtered_actions = {
            'user': [],
            'folder': [],
            'object': [],
            'global': [],
            'workflow': []
        }

        for action in actions:
            catlist = filtered_actions.setdefault(action['category'], [])
            catlist.append(action)

        return filtered_actions


InitializeClass(ActionsTool)
registerToolInterface('portal_actions', IActionsTool)
Exemplo n.º 45
0
        # Delete members' home folders including all content items.
        if delete_memberareas:
            for member_id in member_ids:
                self.deleteMemberArea(member_id)

        # Delete members' local roles.
        if delete_localroles:
            self.deleteLocalRoles(getUtility(ISiteRoot), member_ids,
                                  reindex=1, recursive=1)

        return tuple(member_ids)

    security.declarePublic('getHomeFolder')
    def getHomeFolder(self, id=None, verifyPermission=0):
        """Returns a member's home folder object or None.
        Set verifyPermission to 1 to return None when the user
        doesn't have the View permission on the folder.
        """
        return None

    security.declarePublic('getHomeUrl')
    def getHomeUrl(self, id=None, verifyPermission=0):
        """Returns the URL to a member's home folder or None.
        Set verifyPermission to 1 to return None when the user
        doesn't have the View permission on the folder.
        """
        return None

InitializeClass(MembershipTool)
registerToolInterface('portal_membership', IMembershipTool)
Exemplo n.º 46
0
                            icon_path,
                            binary=0,
                            globs=None,
                            REQUEST=None):
        """Edit a mime type by name
        """
        mt = self.lookup(name)[0]
        self.unregister(mt)
        mt.edit(new_name,
                mimetypes,
                extensions,
                icon_path=icon_path,
                binary=binary,
                globs=globs)
        self.register(mt)
        if REQUEST is not None:
            REQUEST['RESPONSE'].redirect(self.absolute_url() + '/manage_main')


InitializeClass(MimeTypesRegistry)
registerToolInterface('mimetypes_registry', IMimetypesRegistryTool)


def split(name):
    """ split a mime type in a (major / minor) 2-uple """
    try:
        major, minor = name.split('/', 1)
    except:
        raise MimeTypeException('Malformed MIME type (%s)' % name)
    return major, minor
Exemplo n.º 47
0
            tool.setLanguageCookie(langs[0], noredir=True)

        self.default_language = langs[-1]
        self.language = langs[0]
        self.language_list= langs[1:-1]


class PrefsForPTS:
    """A preference to hook into PTS."""
    def __init__(self, context):
        self._env = context
        self.languages = []
        binding = context.get('LANGUAGE_TOOL')
        if not isinstance(binding, LanguageBinding):
            return None
        self.pref = binding.getLanguageBindings()
        self.languages = [self.pref[0]] + self.pref[2] + [self.pref[1]]
        return None

    def getPreferredLanguages(self):
        """Returns the list of the bound languages."""
        return self.languages


if _hasPTS:
    registerLangPrefsMethod({'klass':PrefsForPTS, 'priority':100 })

InitializeClass(LanguageTool)
registerToolInterface('portal_languages', ILanguageTool)

Exemplo n.º 48
0
    security.declarePrivate('unrestrictedGetBrain')

    def unrestrictedGetBrain(self, uid):
        """See IUniqueIdUnrestrictedQuery.
        """
        return self._getBrain(uid, self.unrestrictedQueryBrain)

    security.declarePrivate('unrestrictedGetObject')

    def unrestrictedGetObject(self, uid):
        """See IUniqueIdUnrestrictedQuery.
        """
        return self.unrestrictedGetBrain(uid).getObject()

    security.declarePrivate('unrestrictedQueryObject')

    def unrestrictedQueryObject(self, uid, default=None):
        """See IUniqueIdUnrestrictedQuery.
        """
        try:
            return self.unrestrictedGetObject(uid)
        except UniqueIdError:
            return default

    security.declareProtected(ManagePortal, 'manage_queryObject')
    manage_queryObject = PageTemplateFile('queryUID.pt', _wwwdir)


InitializeClass(UniqueIdHandlerTool)
registerToolInterface('portal_uidhandler', IUniqueIdHandler)
Exemplo n.º 49
0
    security.declarePublic( 'isDiscussionAllowedFor' )
    def isDiscussionAllowedFor( self, content ):
        """ Get boolean indicating whether discussion is allowed for content.
        """
        if hasattr( aq_base(content), 'allow_discussion' ):
            return bool(content.allow_discussion)

        if IDynamicType.providedBy(content):
            # Grabbing type information objects only works for dynamic types
            typeInfo = content.getTypeInfo()
            if typeInfo:
                return bool( typeInfo.allowDiscussion() )

        return False

    #
    #   Utility methods
    #
    security.declarePrivate( '_createDiscussionFor' )
    def _createDiscussionFor( self, content ):
        """ Create DiscussionItemContainer for content, if allowed.
        """
        if not self.isDiscussionAllowedFor( content ):
            raise DiscussionNotAllowed

        content.talkback = DiscussionItemContainer()
        return content.talkback

InitializeClass( DiscussionTool )
registerToolInterface('portal_discussion', IDiscussionTool)
Exemplo n.º 50
0
    security.declarePublic('createChangeSet')

    def createChangeSet(self, ob1, ob2, id1=None, id2=None):
        """Returns a ChangeSet object that represents the differences
        between ob1 and ob2 (ie. ob2 - ob1) ."""
        # FIXME: Pick a better ID
        cs = BaseChangeSet('Changes').__of__(self)
        cs.computeDiff(ob1, ob2, id1=id1, id2=id2)
        return aq_base(cs)


def registerDiffType(klass):
    """Register a class for computing differences.

    Instances of the class must implement the IDifference
    interface."""

    CMFDiffTool._difftypes[klass.meta_type] = klass


def unregisterDiffType(klass):
    """Register a class for computing differences.

    Instances of the class must implement the IDifference
    interface."""

    del CMFDiffTool._difftypes[klass.meta_type]

InitializeClass(CMFDiffTool)
registerToolInterface('portal_diff', IDiffTool)
Exemplo n.º 51
0
                     )

    #
    #   ZMI methods
    #
    security.declareProtected(ManagePortal, 'manage_overview')
    manage_overview = DTMLFile( 'explainPropertiesTool', _dtmldir )

    #
    #   'portal_properties' interface methods
    #
    security.declareProtected(ManagePortal, 'editProperties')
    def editProperties(self, props):
        '''Change portal settings'''
        site = getUtility(ISiteRoot)
        site.manage_changeProperties(props)
        getUtility(IMailHost).smtp_host = props['smtp_server']
        if hasattr(self, 'propertysheets'):
            ps = self.propertysheets
            if hasattr(ps, 'props'):
                ps.props.manage_changeProperties(props)

    def title(self):
        return getUtility(ISiteRoot).title

    def smtp_server(self):
        return getUtility(IMailHost).smtp_host

InitializeClass(PropertiesTool)
registerToolInterface('portal_properties', IPropertiesTool)
Exemplo n.º 52
0
        """
        if not self._default_cataloging:
            return

        if hasattr(aq_base(ob), 'reindexObject'):
            # XXX We only need the keys here, no need to compute values.
            mapping = self.getCatalogVariablesFor(ob) or {}
            vars = mapping.keys()
            ob.reindexObject(idxs=vars)

        # Reindex security of subobjects.
        if hasattr(aq_base(ob), 'reindexObjectSecurity'):
            ob.reindexObjectSecurity()

InitializeClass(WorkflowTool)
registerToolInterface('portal_workflow', IWorkflowTool)


class DefaultWorkflowStatus(object):
    implements(IWorkflowStatus)
    adapts(IWorkflowAware, IWorkflowDefinition)

    def __init__(self, context, workflow):
        self.context = aq_base(context)
        self.wf_id = workflow.getId()

    def get(self):
        history = getattr(self.context, 'workflow_history', {})
        wfh = history.get(self.wf_id)
        if wfh:
            return wfh[-1]
Exemplo n.º 53
0
        year = int(year)

        begin = DateTime('%d/%02d/%02d 00:00:00' % (year, month, day))
        end = DateTime('%d/%02d/%02d 23:59:59' % (year, month, day))

        return (begin, end)

    security.declarePublic('getNextEvent')
    def getNextEvent(self, start_date=None):
        """ Get the next event that starts after start_date
        
        start_date is expected to be a DateTime instance
        """
        if start_date is None:
            start_date = DateTime()

        ctool = getUtility(ICatalogTool)
        query = ctool(
                    portal_type=self.getCalendarTypes(),
                    review_state=self.getCalendarStates(),
                    start={'query': start_date, 'range': 'min'},
                    sort_on='start')

        results = unique_results(query)
        if results:
            results.sort(sort_by_date)
            return results[0]

InitializeClass(CalendarTool)
registerToolInterface('portal_calendar', ICalendarTool)
Exemplo n.º 54
0
                        raise
                    except:
                        logger.error(
                            "Exception was thrown while updating "
                            "role mappings",
                            exc_info=True)
                        if not swallow_errors:
                            raise
                logger.info("Your Plone instance is now up-to-date.")

            if dry_run:
                logger.info("Dry run selected, transaction aborted")
                transaction.abort()

            return stream.getvalue()

        finally:
            logger.removeHandler(handler)
            gslogger.removeHandler(handler)

    upgrade = postonly(upgrade)


def registerUpgradePath(oldversion, newversion, function):
    """ Basic register func """
    pass


InitializeClass(MigrationTool)
registerToolInterface('portal_migration', IMigrationTool)
            new_filelist = [x.getId() for x in result]
            old_filelist = hassession and request.SESSION.get('ploneboard_uploads', []) or []
            for removed in [f for f in old_filelist if f not in new_filelist]:
                del request.SESSION[f]
            if hassession or new_filelist:
                request.SESSION['ploneboard_uploads'] = new_filelist

        return result

    security.declareProtected(View, 'clearUploadedFiles')
    def clearUploadedFiles(self):
        # Get previously uploaded files with a reference in request
        # + files uploaded in this request
        # XXX Add variable to keep track of filenames?
        request = self.REQUEST

        sdm = getToolByName(self, 'session_data_manager', None)

        if sdm is not None:
            if sdm.hasSessionData():
                old_filelist = request.SESSION.get('ploneboard_uploads', None)
                if old_filelist is not None:
                    for file in old_filelist:
                        if request.SESSION.has_key(file):
                            del request.SESSION[file]
                    del request.SESSION['ploneboard_uploads']


Globals.InitializeClass(PloneboardTool)
registerToolInterface(PLONEBOARD_TOOL, IPloneboardTool)
Exemplo n.º 56
0
# -*- coding: utf-8 -*-
from plone.i18n.interfaces import ILanguageUtility
from Products.CMFCore.utils import registerToolInterface

registerToolInterface('portal_languages', ILanguageUtility)
Exemplo n.º 57
0
        """Set the max workflow chain length"""
        safeEditProperty(self, 'max_chain_length', max_chain_length, data_type='int')

_workflow_policy_factories = {}

def _makeWorkflowPolicyFactoryKey(factory, id=None, title=None):
    # The factory should take one argument, id.
    if id is None:
        id = getattr(factory, 'id', '') or getattr(factory, 'meta_type', '')
    if title is None:
        title = getattr(factory, 'title', '')
    key = id
    if title:
        key = key + ' (%s)' % title
    return key

def addWorkflowPolicyFactory(factory, id=None, title=None):
    key = _makeWorkflowPolicyFactoryKey( factory, id, title )
    _workflow_policy_factories[key] = factory

def _removeWorkflowPolicyFactory( factory, id=None, title=None ):
    """ Make teardown in unitcase cleaner. """
    key = _makeWorkflowPolicyFactoryKey( factory, id, title )
    try:
        del _workflow_policy_factories[key]
    except KeyError:
        pass

InitializeClass(PlacefulWorkflowTool)
registerToolInterface('portal_placeful_workflow', IPlacefulWorkflowTool)
Exemplo n.º 58
0
    security.declarePublic('undo')

    def undo(self, object, transaction_info):
        """
            Undo the list of transactions passed in 'transaction_info',
            first verifying that the current user is allowed to undo them.
        """
        # Belt and suspenders:  make sure that the user is actually
        # allowed to undo the transation(s) in transaction_info.

        xids = {}  # set of allowed transaction IDs

        allowed = self.listUndoableTransactionsFor(object)

        for xid in map(lambda x: x['id'], allowed):
            xids[xid] = 1

        if type(transaction_info) == type(''):
            transaction_info = [transaction_info]

        for tinfo in transaction_info:
            if not xids.get(tinfo, None):
                raise AccessControl_Unauthorized

        object.manage_undo_transactions(transaction_info)


InitializeClass(UndoTool)
registerToolInterface('portal_undo', IUndoTool)