Ejemplo n.º 1
0
class ContainerPolicyRegistry(SilvaService):
    meta_type = 'Silva Container Policy Registry'
    grok.implements(IContainerPolicyService)
    grok.name('service_containerpolicy')
    silvaconf.default_service()

    security = ClassSecurityInfo()

    def __init__(self, *args, **kwargs):
        super(ContainerPolicyRegistry, self).__init__(*args, **kwargs)
        self.__policies = {}
        self.register('None', NothingPolicy, 100)

    security.declareProtected('Access contents information', 'get_policy')

    def get_policy(self, name):
        return self.__policies[name][0]

    security.declareProtected('Access contents information', 'list_policies')

    def list_policies(self):
        sorted_policies = []
        for key, value in list(self.__policies.items()):
            insort_right(sorted_policies, _Policy(key, value[1]))
        return [p._name for p in sorted_policies]

    security.declareProtected('Access contents information',
                              'list_addable_policies')

    def list_addable_policies(self, content):
        allowed_addables = IAddableContents(content).get_authorized_addables()
        return [
            p for p in self.list_policies()
            if p in allowed_addables or p == 'None'
        ]

    security.declareProtected('View management screens', 'register')

    def register(self, name, policy, priority=0.0):
        """Register policy.
        """
        assert IContainerPolicy.implementedBy(policy)
        self.__policies[name] = (policy(), priority)
        self._p_changed = 1

    security.declareProtected('View management screens', 'unregister')

    def unregister(self, name):
        """Unregister policy.
        """
        try:
            del self.__policies[name]
        except KeyError:
            pass
        self._p_changed = 1
Ejemplo n.º 2
0
class FilteringService(SilvaService):
    meta_type = 'Silva Filtering Service'
    grok.implements(IContentFilteringService)
    grok.name('service_filtering')
    silvaconf.default_service()

    def filter(self, request):
        return registry(request)

    def contents(self, contents, request):
        return self.filter(request)(contents)
Ejemplo n.º 3
0
class FilesService(SilvaService):
    meta_type = 'Silva Files Service'
    grok.implements(IFilesService, ISilvaConfigurableService)
    grok.name('service_files')
    silvaconf.default_service()
    silvaconf.icon('icons/service_files.png')

    security = ClassSecurityInfo()

    storage = FieldProperty(IFilesService['storage'])

    manage_options = ({
        'label': 'Settings',
        'action': 'manage_settings'
    }, ) + SilvaService.manage_options

    security.declarePrivate('new_file')

    def new_file(self, id):
        if self.storage is None:
            return ZODBFile(id)
        return self.storage(id)

    security.declarePrivate('upgrade_storage')

    def convert_storage(self, container):
        if self.storage is not None and self.storage is not ZODBFile:
            upg = upgrade.UpgradeRegistry()
            upg.register(StorageConverterHelper(container), '0.1',
                         upgrade.AnyMetaType)
            upg.register(FileStorageConverter(self), '0.1', 'Silva File')
            upg.register(ImageStorageConverter(self), '0.1', 'Silva Image')
            upg.upgrade_tree(container, '0.1')

    def is_file_using_correct_storage(self, content):
        storage = ZODBFile
        if self.storage is not None:
            storage = self.storage
        return isinstance(content, storage)
Ejemplo n.º 4
0
class ExtensionService(SilvaService, Folder):
    meta_type = 'Silva Extension Service'
    grok.implements(IExtensionService, ISilvaConfigurableService)
    grok.name('service_extensions')
    silvaconf.default_service()
    silvaconf.icon('icons/service_extension.png')

    security = ClassSecurityInfo()
    manage_options = (
        {
            'label': 'Extensions',
            'action': 'manage_extensions'
        },
        {
            'label': 'Partial upgrades',
            'action': 'manage_partialUpgrade'
        },
        {
            'label': 'Partial reindex',
            'action': 'manage_partialReindex'
        },
        {
            'label': 'Logs',
            'action': 'manage_main'
        },
    ) + SilvaService.manage_options

    _site_quota = 0
    _quota_enabled = False
    _quota_verify = False

    # MANIPULATORS

    security.declareProtected('View management screens', 'install')

    def install(self, name):
        """Install extension
        """
        root = self.get_root()
        extensionRegistry.install(name, root)

    security.declareProtected('View management screens', 'uninstall')

    def uninstall(self, name):
        """Uninstall extension
        """
        root = self.get_root()
        extensionRegistry.uninstall(name, root)

    security.declareProtected('View management screens', 'refresh')

    def refresh(self, name):
        """Refresh  extension.
        """
        root = self.get_root()
        extensionRegistry.refresh(name, root)

    security.declareProtected('View management screens', 'refresh_all')

    def refresh_all(self):
        """Refreshes all extensions
        """
        for name in extensionRegistry.get_names():
            if self.is_installed(name):
                self.refresh(name)

    security.declareProtected('View management screens', 'reindex_all')

    def reindex_all(self):
        """Refresh the silva catalog.
        """
        root = self.get_root()
        root.service_catalog.manage_catalogClear()
        logger.info('Catalog cleared.')
        index_content(root)

    security.declareProtected('View management screens', 'reindex_subtree')

    def reindex_subtree(self, path):
        """reindexes a subtree.
        """
        root = self.get_root()
        index_content(root.unrestrictedTraverse(str(path)), reindex=True)

    security.declareProtected('View management screens',
                              'disable_quota_subsystem')

    def disable_quota_subsystem(self):
        """Disable quota sub-system.
        """
        if not self._quota_enabled:
            return False
        if self._site_quota:
            # You cannot disable the quota system if there is a site quota.
            return False
        root = self.get_root()

        # Disable metadata for quota
        collection = root.service_metadata.getCollection()
        if 'silva-quota' in collection.objectIds():
            collection.manage_delObjects(['silva-quota'])
        setids = ('silva-quota', )
        types = (
            'Silva Root',
            'Silva Publication',
        )
        root.service_metadata.removeTypesMapping(types, setids)

        self._quota_enabled = False
        self._quota_verify = False
        return True

    security.declareProtected('View management screens',
                              'enable_quota_subsystem')

    def enable_quota_subsystem(self):
        """Enable quota sub-system.
        """
        if self._quota_enabled:
            return False
        root = self.get_root()

        # Setup metadata for quota
        schema = os.path.join(os.path.dirname(__file__), 'schema')

        collection = root.service_metadata.getCollection()
        if 'silva-quota' in collection.objectIds():
            collection.manage_delObjects(['silva-quota'])

        xml_file = os.path.join(schema, 'silva-quota.xml')
        with open(xml_file, 'r') as fh:
            collection.importSet(fh)

        setids = ('silva-quota', )
        types = [
            c['name']
            for c in extensionRegistry.get_contents(requires=[IPublication])
        ]
        root.service_metadata.addTypesMapping(types, setids)
        root.service_metadata.initializeMetadata()

        root.used_space = compute_used_space(root)
        self._quota_enabled = True
        self._quota_verify = True
        return True

    security.declareProtected('View management screens', 'upgrade_content')

    def upgrade_content(self, content, from_version, to_version):
        """Upgrade the given content
        """
        now = datetime.now().strftime('%Y-%b-%dT%H%M%S')
        log_filename = 'upgrade-log-%s-to-%s-on-%s.log' % (from_version,
                                                           to_version, now)
        log = upgrade.registry.upgrade(content, from_version, to_version)
        factory = self.manage_addProduct['OFS']
        factory = factory.manage_addFile(log_filename,
                                         log.read(),
                                         content_type='text/plain')
        if interfaces.IRoot.providedBy(content):
            content._content_version = to_version

    # ACCESSORS

    security.declareProtected('Access contents information',
                              'get_quota_subsystem_status')

    def get_quota_subsystem_status(self):
        if not self._quota_enabled:
            return None
        return self._quota_verify

    security.declareProtected('Access contents information', 'get_site_quota')

    def get_site_quota(self):
        return self._site_quota

    security.declareProtected('Access contents information', 'is_installed')

    def is_installed(self, name):
        """Is extension installed?
        """
        root = self.get_root()
        return extensionRegistry.is_installed(name, root)
Ejemplo n.º 5
0
class EmailMessageService(SilvaService):
    """Simple implementation of IMemberMessageService that sends email
    messages.
    """
    meta_type = 'Silva Message Service'
    grok.implements(interfaces.IMessageService, ISilvaConfigurableService)
    grok.name('service_messages')
    silvaconf.default_service()
    silvaconf.icon('icons/service_message.png')

    manage_options = (
        {'label':'Settings', 'action':'manage_settings'},
        ) + SilvaService.manage_options

    security = ClassSecurityInfo()

    _fromaddr = None
    _enabled = False

    # XXX these security settings are not the right thing.. perhaps
    # create a new permission?
    security.declareProtected(
        SilvaPermissions.ChangeSilvaAccess, 'send_message')
    def send_message(self, from_memberid, to_memberid, subject, message):
        email_queue.enqueue_email(
            from_memberid, to_memberid, subject, message)

    security.declarePublic('send_pending_messages')
    def send_pending_messages(self):
        logger.debug("Sending pending messages...")

        service_members = getUtility(IMemberService)
        get_member = service_members.get_member

        for to_memberid, message_dict in email_queue:
            to_member = get_member(to_memberid)
            if to_member is None:
                # XXX get_member should return a NoneMember, not just None
                # in case the member cannot be found. Apparently sometimes
                # it *does* return.
                logger.debug("no member found for: %s" % to_memberid)
                continue
            to_email = to_member.email()
            if to_email is None:
                logger.debug("no email for: %s" % to_memberid)
                continue
            lines = []
            # XXX usually all messages have the same subject yet,
            # but this can be assumed here per se.
            common_subject=None
            reply_to = {}
            for from_memberid, messages in message_dict.items():
                logger.debug("From memberid: %s " % from_memberid)
                from_member = get_member(from_memberid)
                if from_member is None:
                    # XXX get_member should return a NoneMember, not just None
                    # in case the member cannot be found. Apparently sometimes
                    # it *does* return.
                    logger.debug("no member found for: %s" % to_memberid)
                    continue
                from_email = from_member.email()
                if from_email is not None:
                    reply_to[from_email] = 1
                    lines.append("Message from: %s (email: %s)" %
                                 (from_memberid, from_email))
                else:
                    lines.append("Message from: %s (no email available)" %
                                 from_memberid)
                for subject, message in messages:
                    lines.append(subject)
                    lines.append('')
                    lines.append(message)
                    lines.append('')
                    if common_subject is None:
                        common_subject = subject
                    else:
                        if common_subject != subject:
                            # XXX this is very stupid, but what else?
                            # maybe leave empty?
                            common_subject = 'Notification on status change'

            text = '\n'.join(lines)
            header = {}
            if common_subject is not None:
                header['Subject'] = common_subject
            if reply_to:
                header['Reply-To'] = ', '.join(reply_to.keys())
                # XXX set from header ?
            self._send_email(to_email, text, header=header)

        # XXX if above raises exception: mail queue is not flushed
        # as this line is not reached. bug or feature ?
        email_queue.clear()

    # ACCESSORS
    security.declareProtected(SilvaPermissions.ViewManagementScreens,
                              'fromaddr')
    def fromaddr(self):
        """return self._fromaddr"""
        return self._fromaddr

    security.declareProtected(SilvaPermissions.ViewManagementScreens,
                              'send_email_enabled')
    def send_email_enabled(self):
        return self._enabled

    def _send_email(self, toaddr, msg, header={}):
        if not self._enabled:
            return
        header['To'] = toaddr
        if not header.has_key('From'):
            header['From'] = self._fromaddr
        if not header.has_key('Sender'):
            header['Sender'] = self._fromaddr
        header['Content-Type'] = 'text/plain; charset=UTF-8'

        msg_lines = [ '%s: %s' % (k, v) for k, v in header.items() ]
        msg_lines.append('')
        msg_lines.append(msg)
        msg = '\r\n'.join(msg_lines)
        if isinstance(msg, unicode):
            msg = msg.encode('UTF-8')

        # Send the email using the mailhost
        sendmail(self, msg, toaddr, self._fromaddr)