Ejemplo n.º 1
0
def encode(data, schema, ignore=()):
    """Given a data dictionary with key/value pairs and schema, return an
    encoded query string. This is similar to urllib.urlencode(), but field
    names will include the appropriate field type converters, e.g. an int
    field will be encoded as fieldname:int=123. Fields not found in the data
    dict will be ignored, and items in the dict not in the schema will also
    be ignored. Additional fields to ignore can be passed with the 'ignore'
    parameter. If any fields cannot be converted, a ComponentLookupError
    will be raised.
    """

    encode = []

    for name, field in getFieldsInOrder(schema):
        if name in ignore or name not in data:
            continue

        converter = IFieldTypeConverter(field, None)
        if converter is None:
            raise ComponentLookupError(u"Cannot URL encode %s of type %s" % (
                name, field.__class__,))

        encoded_name = name
        if converter.token:
            encoded_name = "%s:%s" % (name, converter.token,)

        value = data[name]
        if value is None:
            continue

        if ISequence.providedBy(field):
            value_type_converter = IFieldTypeConverter(field.value_type, None)
            if value_type_converter is None:
                raise ComponentLookupError(
                    u"Cannot URL encode value type for %s of type %s : %s" % (
                        name, field.__class__, field.value_type.__class__,))

            if value_type_converter.token:
                encoded_name = "%s:%s:%s" % (
                    name, value_type_converter.token, converter.token,)

            for item in value:

                if isinstance(item, bool):
                    item = item and '1' or ''

                encode.append((encoded_name, item,))

        else:
            # The :bool converter just does bool() value, but urlencode() does
            # str() on the object. The result is False => 'False' => True :(
            if isinstance(value, bool):
                value = value and '1' or ''

            encode.append((encoded_name, value))

    return urllib.urlencode(encode)
Ejemplo n.º 2
0
def getInterface(context, id):
    """Return interface or raise ComponentLookupError

    >>> from zope.interface import Interface
    >>> from zope.component.tests import ITestType

    >>> class I4(Interface):
    ...     pass
    >>> IInterface.providedBy(I4)
    True
    >>> ITestType.providedBy(I4)
    False
    >>> getInterface(None, 'zope.component.interface.I4')
    Traceback (most recent call last):
    ...
    ComponentLookupError: zope.component.interface.I4
    >>> provideInterface('', I4, ITestType)
    >>> ITestType.providedBy(I4)
    True
    >>> iface = queryInterface( """\
                """ 'zope.component.interface.I4')
    >>> iface.__name__
    'I4'
    """
    iface = queryInterface(id, None)
    if iface is None:
        raise ComponentLookupError(id)
    return iface
Ejemplo n.º 3
0
 def getUtility(self, interface, name=''):
     """See IFiveUtilityRegistry interface
     """
     c = self.queryUtility(interface, name)
     if c is not None:
         return c
     raise ComponentLookupError(interface, name)
    def consumeActions(self, content, token, **kwargs):
        self.verifyToken(content, token)
        actions = self.consumeToken(content, token)
        results = []

        for action in actions:
            action_type = action.type

            try:
                adapter = getMultiAdapter((content, content.REQUEST),
                                          IPowerActionProvider,
                                          name=action_type)
            except ComponentLookupError:
                raise ComponentLookupError(
                    'Cannot find a provider for performing action "%s" on %s' %
                    (action_type, '/'.join(content.getPhysicalPath())))
            try:
                if action.roles or action.unrestricted:
                    acl_users = getToolByName(content, 'acl_users')
                    old_sm = getSecurityManager()
                    Cls = SimpleUser
                    if action.unrestricted:
                        Cls = UnrestrictedUser
                    tmp_user = Cls(
                        action.username or old_sm.getUser().getId() or '', '',
                        action.roles, '')
                    tmp_user = tmp_user.__of__(acl_users)
                    newSecurityManager(None, tmp_user)
                results.append(adapter.doAction(action, **kwargs))
            finally:
                if action.roles:
                    setSecurityManager(old_sm)
        return results
Ejemplo n.º 5
0
def getInterface(context, id):
    """Return interface or raise ComponentLookupError
    """
    iface = queryInterface(id, None)
    if iface is None:
        raise ComponentLookupError(id)
    return iface
Ejemplo n.º 6
0
    def test_register_with_name(self):
        register_session('sqlite://','foo')

        # check registrations
        compare(generator(
                C('zope.component.registry.UtilityRegistration',
                  component=C('sqlalchemy.orm.scoping.ScopedSession'),
                  factory=None,
                  info=u'',
                  name=u'foo',
                  provided=ISession,
                  registry=self.components.registry
                  )),self.components.registry.registeredUtilities())
        
        registry = getSiteManager()
        
        # check we don't register with no name:
        with ShouldRaise(ComponentLookupError(ISession, u'')):
            registry.getUtility(ISession)

        # check we do with the right name
        self.failUnless(isinstance(
                registry.getUtility(ISession,'foo')(),
                Session
                ))
    def __call__(self):
        mailhost = getToolByName(aq_inner(self.context), "MailHost")
        if not mailhost:
            raise ComponentLookupError("You must have a Mailhost utility to "
                                       "execute this action")
        source = self.element.source
        urltool = getToolByName(aq_inner(self.context), "portal_url")
        portal = urltool.getPortalObject()
        email_charset = portal.getProperty("email_charset")
        if not source:
            # no source provided, looking for the site wide from email
            # address
            from_address = portal.getProperty("email_from_address")
            if not from_address:
                raise ValueError(
                    "You must provide a source address for this "
                    "action or enter an email in the portal properties")
            from_name = portal.getProperty("email_from_name")
            source = "%s <%s>" % (from_name, from_address)
        plone_view = portal.restrictedTraverse("@@plone")
        obj = self.event.object
        dest = obj.getEmail()
        message = self.element.message
        message = message.replace(
            "${date}", plone_view.toLocalizedTime(obj.getData_prenotazione()))
        message = message.replace("${url}", obj.absolute_url())
        message = message.replace("${title}", self.check_uni(obj.Title()))
        message = message.replace("${portal}", self.check_uni(portal.Title()))
        subject = self.element.subject
        subject = subject.replace("${url}", obj.absolute_url())
        subject = subject.replace("${title}", self.check_uni(obj.Title()))
        subject = subject.replace("${portal}", self.check_uni(portal.Title()))

        self.context.plone_log("sending to: %s" % dest)
        try:
            # sending mail in Plone 4
            mailhost.send(
                message,
                mto=dest,
                mfrom=source,
                subject=subject,
                charset=email_charset,
            )
        except Exception:
            # sending mail in Plone 3
            mailhost.secureSend(
                message,
                dest,
                source,
                subject=subject,
                subtype="plain",
                charset=email_charset,
                debug=False,
            )

        return True
Ejemplo n.º 8
0
    def __call__(self):
        mailhost = getToolByName(aq_inner(self.context), "MailHost")

        if not mailhost:
            raise ComponentLookupError(
                'You must have a Mailhost utility to execute this action')

        source = self.element.source
        urltool = getToolByName(aq_inner(self.context), "portal_url")
        portal = urltool.getPortalObject()
        email_charset = portal.getProperty('email_charset')
        if not source:
            # no source provided, looking for the site wide from email
            # address
            from_address = portal.getProperty('email_from_address')
            if not from_address:
                raise ValueError("You must provide a source address for this \
action or enter an email in the portal properties")
            from_name = portal.getProperty('email_from_name').strip('"')
            source = '"%s" <%s>' % (from_name, from_address)

        obj = self.event.object

        interpolator = IStringInterpolator(obj)
        rules_tool = getToolByName(aq_inner(self.context),
                                   'contentrules_subscription_tool')
        recipients_mail = rules_tool.getRegisteredList(self.element.actionUID)

        # Prepend interpolated message with \n to avoid interpretation
        # of first line as header.
        message = "\n%s" % interpolator(self.element.message)
        subject = interpolator(self.element.subject)
        logger.info("Sending mail to recipients: %s" %
                    ", ".join(recipients_mail))
        for recipient in recipients_mail:
            try:
                # XXX: We're using "immediate=True" because otherwise we won't
                # be able to catch SMTPException as the smtp connection is made
                # as part of the transaction apparatus.
                # AlecM thinks this wouldn't be a problem if mail queuing was
                # always on -- but it isn't. (stevem)
                # so we test if queue is not on to set immediate
                mailhost.send(message,
                              recipient,
                              source,
                              subject=subject,
                              charset=email_charset,
                              immediate=not mailhost.smtp_queue)
            except (MailHostError, SMTPException):
                logger.error(
                    """mailing error: Attempt to send mail in content rule failed.\n%s"""
                    % traceback.format_exc())
        return True
Ejemplo n.º 9
0
def getSiteManager(context=None):
    global base
    if context is None:
        if base is None:
            from zope.component.globalregistry import base
        return base
    else:
        # Use the global site manager to adapt context to `IComponentLookup`
        # to avoid the recursion implied by using a local `getAdapter()` call.
        try:
            return IComponentLookup(context)
        except TypeError, error:
            raise ComponentLookupError(*error.args)
Ejemplo n.º 10
0
    def __call__(self):
        mailhost = getToolByName(aq_inner(self.context), 'MailHost')
        if not mailhost:
            raise ComponentLookupError('You must have a Mailhost utility to \
execute this action')

        self.email_charset = self.mail_settings.email_charset

        obj = self.event.object

        interpolator = IStringInterpolator(obj)

        self.source = self.element.source
        if self.source:
            self.source = interpolator(self.source).strip()

        if not self.source:
            # no source provided, looking for the site wide from email
            # address
            from_address = self.mail_settings.email_from_address
            if not from_address:
                # the mail can't be sent. Try to inform the user
                request = getRequest()
                if request:
                    messages = IStatusMessage(request)
                    msg = _(
                        u'Error sending email from content rule. You must '
                        'provide a source address for mail '
                        'actions or enter an email in the portal properties')
                    messages.add(msg, type=u'error')
                return False
            from_name = self.mail_settings.email_from_name.strip('"')
            self.source = u'{0} <{1}>'.format(from_name, from_address)

        self.recipients = self.get_recipients()

        # prepend interpolated message with \n to avoid interpretation
        # of first line as header
        self.message = u'\n{0!s}'.format(interpolator(self.element.message))

        self.subject = interpolator(self.element.subject)

        mime_msg = self.create_mime_msg()
        if not mime_msg:
            return False

        # Finally send mail.
        # Plone-4
        mailhost.send(mime_msg)

        return True
Ejemplo n.º 11
0
 def _checkForZCARegistry(*args, **kwargs):
     sm = getSiteManager()
     configured = False
     for a in sm.registeredAdapters():
         configured = True
         break
     for h in sm.registeredSubscriptionAdapters():
         configured = True
         break
     for u in sm.registeredUtilities():
         configured = True
         break
     for h in sm.registeredHandlers():
         configured = True
         break
     if not configured:
         raise ComponentLookupError(
             "Use of this class requires sparc component registration.")
     return classThatRequiresConfigration(*args, **kwargs)
Ejemplo n.º 12
0
def getUtilityByInterfaceName(dotted_name, default=_marker):
    """ Get a tool by its fully-qualified dotted interface path

    This method replaces getToolByName for use in untrusted code.
    Trusted code should use zope.component.getUtility instead.
    """
    try:
        iface = resolve_dotted_name(dotted_name)
    except ImportError:
        if default is _marker:
            raise ComponentLookupError(dotted_name)
        return default

    try:
        return getUtility(iface)
    except ComponentLookupError:
        if default is _marker:
            raise
        return default
    def __call__(self):
        portal_membership = getToolByName(aq_inner(self.context),
                                          'portal_membership')
        portal_groups = getToolByName(aq_inner(self.context), 'portal_groups')

        members = set(self.element.members)

        recipients = set()

        for groupId in self.element.groups:
            group = portal_groups.getGroupById(groupId)

            if group and group.getProperties().get('email'):
                recipients.update([group.getProperties().get('email')], )

            groupMembers = group.getGroupMemberIds()
            for memberId in groupMembers:
                members.update([
                    memberId,
                ])

        for memberId in members:
            member = portal_membership.getMemberById(memberId)
            if member and member.getProperty('email'):
                recipients.update([
                    member.getProperty('email'),
                ])

        mailhost = getToolByName(aq_inner(self.context), 'MailHost')
        if not mailhost:
            raise ComponentLookupError('You must have a Mailhost utility to \
execute this action')

        source = from_address = self.element.source
        urltool = getToolByName(aq_inner(self.context), 'portal_url')
        portal = urltool.getPortalObject()
        email_charset = portal.getProperty('email_charset')
        if not source:
            # no source provided, looking for the site wide from email
            # address
            from_address = portal.getProperty('email_from_address')
            if not from_address:
                raise ValueError('You must provide a source address for this \
action or enter an email in the portal properties')
            from_name = portal.getProperty('email_from_name')
            source = '%s <%s>' % (from_name, from_address)

        obj = self.event.object
        # Not all items have a text-field:
        interpolator = IStringInterpolator(obj)
        message = '\n%s' % interpolator(self.element.message)
        subject = interpolator(self.element.subject)

        # Convert set of recipients to a list:
        list_of_recipients = list(recipients)
        if not list_of_recipients:
            return False
        # Prepare multi-part-message to send html with plain-text-fallback-message,
        # for non-html-capable-mail-clients.
        # Thanks to Peter Bengtsson for valuable information about this in this post:
        # http://www.peterbe.com/plog/zope-html-emails
        mime_msg = MIMEMultipart('related')
        mime_msg['Subject'] = subject
        mime_msg['From'] = source
        # mime_msg['To'] = ""
        mime_msg['Bcc'] = ', '.join(list_of_recipients)
        mime_msg.preamble = 'This is a multi-part message in MIME format.'

        # Encapsulate the plain and HTML versions of the message body
        # in an 'alternative' part, so message agents can decide
        # which they want to display.
        msgAlternative = MIMEMultipart('alternative')
        mime_msg.attach(msgAlternative)

        # Convert html-message to plain text.
        transforms = getToolByName(aq_inner(self.context), 'portal_transforms')
        stream = transforms.convertTo('text/plain',
                                      message,
                                      mimetype='text/html')
        body_plain = stream.getData().strip()

        # We attach the plain text first, the order is mandatory.
        msg_txt = MIMEText(body_plain,
                           _subtype='plain',
                           _charset=email_charset)
        msgAlternative.attach(msg_txt)

        # After that, attach html.
        msg_txt = MIMEText(message, _subtype='html', _charset=email_charset)
        msgAlternative.attach(msg_txt)

        # Finally send mail.
        mailhost.send(mime_msg)

        return True
Ejemplo n.º 14
0
 def getSiteManager(self):
     if self._sm is not None:
         return self._sm
     else:
         raise ComponentLookupError('no site manager defined')
Ejemplo n.º 15
0
 def _adapter_hook(interface, object, name, default):
     _called.append((interface, object, name, default))
     raise ComponentLookupError('testing')
Ejemplo n.º 16
0
    def __call__(self):
                        
        context = obj = self.event.object
        templateContext = getTemplateContext(context)
        
        # Flag if we have errors from any template formatter
        any_errors = False
            
        recipients, errors = applyTemplate(templateContext, self.element.recipients, logger=logger)
        any_errors |= errors
        if recipients == None:
            raise ValueError("Bad recipients value:" + str(self.element.recipients.encode("utf-8")))
            
        emails = recipients.strip().split(",")
        emails = [ email for email in emails if (email != None and email != '')]                
        recipients = [str(email.strip()) for email in emails]
        
        mailhost = getToolByName(aq_inner(self.context), "MailHost")
        if not mailhost:
            raise ComponentLookupError('You must have a Mailhost utility to execute this action')
        
        source = self.element.source
        source, errors = applyTemplate(templateContext, source, logger=logger)
        any_errors |= errors        
        
        urltool = getToolByName(aq_inner(self.context), "portal_url")
        portal = urltool.getPortalObject()
        email_charset = portal.getProperty('email_charset')
        
        if not source or len(source) == 0:
            # no source provided, looking for the site wide from email
            # address
            from_address = portal.getProperty('email_from_address')
            if not from_address:
                raise ValueError, 'You must provide a source address for this \
action or enter an email in the portal properties'
            from_name = portal.getProperty('email_from_name')
            source = "%s <%s>" % (from_name, from_address)

        message, errors = applyTemplate(templateContext, self.element.message, logger=logger)
        any_errors |= errors
        
        #subject_source = self.sanify_encoding(self.element.subject)
        subject_source = self.element.subject

        subject, errors = applyTemplate(templateContext, subject_source, logger=logger)
        any_errors |= errors
        

        
        # TODO: Should these to be added to status messaegs
        if len(recipients) == 0:
            raise ValueError("Recipients could not be defined from template:" + self.element.recipients.encode("utf-8"))

        if subject == None or len(subject) == 0:            
            raise ValueError("Subject could not be defined from template:" + self.element.subject.encode("utf-8"))

        if source == None or len(source) == 0:
            raise ValueError("Source could not be defined from template:" + self.element.source.encode("utf-8"))

        if any_errors:
            # These has been outputted already above
            return
        
        for email_recipient in recipients:
            
            assert len(email_recipient.strip()) > 0, "Email recipient is empty, all recipients:" + str(recipients)

            mailhost.secureSend(message, email_recipient, source,
                                subject=subject, subtype='plain',
                                charset=email_charset, debug=False)

        return True
Ejemplo n.º 17
0
    def __call__(self):
        mailhost = getToolByName(aq_inner(self.context), 'MailHost')
        if not mailhost:
            raise ComponentLookupError(
                'You must have a Mailhost utility to execute this action')

        email_charset = self.mail_settings.email_charset
        obj = self.event.object
        interpolator = IStringInterpolator(obj)
        source = self.element.source

        if source:
            source = interpolator(source).strip()

        if not source:
            # no source provided, looking for the site wide from email
            # address
            from_address = self.mail_settings.email_from_address
            if not from_address:
                # the mail can't be sent. Try to inform the user
                request = getRequest()
                if request:
                    messages = IStatusMessage(request)
                    msg = _(
                        u'Error sending email from content rule. You must '
                        u'provide a source address for mail '
                        u'actions or enter an email in the portal properties')
                    messages.add(msg, type=u'error')
                return False

            from_name = self.mail_settings.email_from_name.strip('"')
            source = '"{0}" <{1}>'.format(from_name.encode('utf8'),
                                          from_address)

        recip_string = interpolator(self.element.recipients)
        if recip_string:  # check recipient is not None or empty string
            recipients = set([
                str(mail.strip()) for mail in recip_string.split(',')
                if mail.strip()
            ])
        else:
            recipients = set()

        if self.element.exclude_actor:
            mtool = getToolByName(aq_inner(self.context), 'portal_membership')
            actor_email = mtool.getAuthenticatedMember().getProperty(
                'email', '')
            if actor_email in recipients:
                recipients.remove(actor_email)

        # prepend interpolated message with \n to avoid interpretation
        # of first line as header
        message = u'\n{0}'.format(interpolator(self.element.message))

        subject = interpolator(self.element.subject)

        for email_recipient in recipients:
            try:
                # XXX: We're using "immediate=True" because otherwise we won't
                # be able to catch SMTPException as the smtp connection is made
                # as part of the transaction apparatus.
                # AlecM thinks this wouldn't be a problem if mail queuing was
                # always on -- but it isn't. (stevem)
                # so we test if queue is not on to set immediate
                mailhost.send(message,
                              email_recipient,
                              source,
                              subject=subject,
                              charset=email_charset,
                              immediate=not mailhost.smtp_queue)
            except (MailHostError, SMTPException):
                logger.exception(
                    'mail error: Attempt to send mail in content rule failed')

        return True
Ejemplo n.º 18
0
def getAdapterInContext(object, interface, context):
    adapter = queryAdapterInContext(object, interface, context)
    if adapter is None:
        raise ComponentLookupError(object, interface)
    return adapter
Ejemplo n.º 19
0
    def __call__(self):
        # mailhost = getToolByName(aq_inner(self.context), "MailHost")
        mailhost = getUtility(IMailHost)

        if not mailhost:
            raise ComponentLookupError(
                'You must have a Mailhost utility to execute this action')

        source = self.element.source
        urltool = getToolByName(aq_inner(self.context), "portal_url")
        membertool = getToolByName(aq_inner(self.context), "portal_membership")

        portal = urltool.getPortalObject()
        if not source:
            # no source provided, looking for the site wide from email
            # address
            from_address = portal.getProperty('email_from_address')
            if IS_PLONE_5:
                from_address = api.portal.get_registry_record(
                    'plone.email_from_address')
            if not from_address:
                raise ValueError("You must provide a source address for this \
action or enter an email in the portal properties")

            from_name = portal.getProperty('email_from_name', '').strip('"')
            if IS_PLONE_5:
                from_name = api.portal.get_registry_record(
                    'plone.email_from_name')
            source = '"%s" <%s>' % (from_name, from_address)

        obj = self.event.object

        interpolator = IStringInterpolator(obj)

        # search through all local roles on the object, and add
        # users's email to the recipients list if they have the local
        # role stored in the action
        local_roles = obj.get_local_roles()
        if len(local_roles) == 0:
            return True
        recipients = set()
        for user, roles in local_roles:
            rolelist = list(roles)
            if self.element.role in rolelist:
                recipients.add(user)

        # check for the acquired roles
        if self.element.acquired:
            sharing_page = obj.unrestrictedTraverse('@@sharing')
            acquired_roles = sharing_page._inherited_roles()
            if hasattr(sharing_page, '_borg_localroles'):
                acquired_roles += sharing_page._borg_localroles()
            acquired_users = [
                r[0] for r in acquired_roles if self.element.role in r[1]
            ]
            recipients.update(acquired_users)

        # check for the global roles
        if self.element.global_roles:
            pas = getToolByName(self.event.object, 'acl_users')
            rolemanager = pas.portal_role_manager
            global_role_ids = [
                p[0]
                for p in rolemanager.listAssignedPrincipals(self.element.role)
            ]
            recipients.update(global_role_ids)

        # check to see if the recipents are users or groups
        group_recipients = []
        new_recipients = []
        group_tool = portal.portal_groups

        def _getGroupMemberIds(group):
            """ Helper method to support groups in groups. """
            members = []
            for member_id in group.getGroupMemberIds():
                subgroup = group_tool.getGroupById(member_id)
                if subgroup is not None:
                    members.extend(_getGroupMemberIds(subgroup))
                else:
                    members.append(member_id)
            return members

        for recipient in recipients:
            group = group_tool.getGroupById(recipient)
            if group is not None:
                group_recipients.append(recipient)
                [
                    new_recipients.append(user_id)
                    for user_id in _getGroupMemberIds(group)
                ]

        for recipient in group_recipients:
            recipients.remove(recipient)

        for recipient in new_recipients:
            recipients.add(recipient)

        # look up e-mail addresses for the found users
        recipients_mail = set()
        for user in recipients:
            member = membertool.getMemberById(user)
            # check whether user really exists
            # before getting its email address
            if not member:
                continue
            recipient_prop = member.getProperty('email')
            if recipient_prop is not None and len(recipient_prop) > 0:
                recipients_mail.add(recipient_prop)

        # Prepend interpolated message with \n to avoid interpretation
        # of first line as header.
        message = "\n%s" % interpolator(self.element.message)
        subject = interpolator(self.element.subject)
        for recipient in recipients_mail:
            try:
                mailhost.send(message,
                              recipient,
                              source,
                              subject=subject,
                              charset='utf-8',
                              msg_type="text/html")
                # logger.info("{} email sent to {}".format(recipient, subject))
            except (MailHostError, SMTPException):
                logger.exception(
                    'mail error: Attempt to send mail in content rule failed')
        return True
Ejemplo n.º 20
0
def send_distribution_list(obj, event):
    if not event.new_state.id in ['shared_intranet']:
        return
    #other
    portal_url = getToolByName(obj, 'portal_url')
    site_email = portal_url.getPortalObject().getProperty('email_from_address')
    
    all_email = list()
    report_authors = obj.report_author
    mission_members = []
    if get_mission(obj):
        mission_members = get_mission(obj).mission_members
    mission_distribution = obj.mission_distribution
    
    for md in mission_distribution or []:
        other_usr = obj.portal_membership.getMemberById(md)
        if other_usr:
            all_email.append(other_usr.getProperty('email'))
    
    distribution_others = obj.mission_distribution_others
    for dist_other in distribution_others or []:
        if validateaddress(dist_other):
            all_email.append(dist_other)
    

    #creator
    creator = obj.Creator()
    creator_info = obj.portal_membership.getMemberInfo(creator)
    creator_full_name = creator_info['fullname']
    creator_email = obj.portal_membership.getMemberById(creator).getProperty('email')
    all_email.append(creator_email)
    
    #for i in set(report_authors + mission_members + [creator]):
    #    email = obj.portal_membership.getMemberById(i).getProperty('email')
    #    all_email.append(email)

    #all_email.extend(mission_distribution)
    filtered_email = list(set(all_email))
    
    
    converter = getUtility(IPDFConverter)
    pdf = converter.convert(obj)

    mailhost = obj.MailHost

    if not mailhost:
        raise ComponentLookupError('You must have a Mailhost utility to'
                                   'execute this action')

    from_address = obj.email_from_address
    if not from_address:
        raise ValueError('You must provide a source address for this'
                         'action or enter an email in the portal properties')
    from_name = obj.email_from_name
    source = "%s <%s>" % (from_name, from_address)

    event_title = safe_unicode(safe_unicode(obj.Title()))
    subject = event_title

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = source
    
    body = """You can view the full report online at:

    %(url)s


    This is a message generated by the system.
    
    ----------
    %(site_name)s
    %(site_email)s
    %(site_url)s

    """ % {
        'url': obj.absolute_url(),
        'site_name': getSite().title,
        'site_email': site_email,
        'site_url': getSite().absolute_url()
    }

    body_safe = body.encode('utf-8')
    htmlPart = MIMEText(body_safe, 'plain', 'utf-8')
    msg.attach(htmlPart)

    # generated pdf attachments

    if pdf:
        attachment = MIMEBase('application', 'pdf')
        attachment.set_payload(pdf.buf)
        Encoders.encode_base64(attachment)
        attachment.add_header('Content-Disposition', 'attachment',
                              filename=subject + '.pdf')
        msg.attach(attachment)

    #attactments in the report
    file_brains = obj.getFolderContents()
    for file_brain in file_brains:
        if file_brain.portal_type == 'File':
            file = file_brain.getObject().getFile()
            ctype = file.getContentType()
            filename = file.filename
            
            maintype, subtype = ctype.split(('/'), 1)
            attachment = MIMEBase(maintype, subtype)
            attachment.set_payload(str(file))
            Encoders.encode_base64(attachment)
            attachment.add_header('Content-Disposition', 'attachment',
                                  filename=filename)
            msg.attach(attachment)
    
    for atch in ['attachment1', 'attachment2', 'attachment3', 'attachment4', 'attachment5']:
        attach = getattr(obj, atch)
        if attach:
            ctype = attach.contentType
            filename = attach.filename
            maintype, subtype = ctype.split(('/'), 1)
            attachment = MIMEBase(maintype, subtype)
            attachment.set_payload(str(attach.data))
            Encoders.encode_base64(attachment)
            attachment.add_header('Content-Disposition', 'attachment', filename=filename)
            msg.attach(attachment)
        

    #send email
    for recipient in filtered_email:
        # skip broken recipients
        if not recipient:
            continue
        if '@' not in recipient:
            continue

        del msg['To']
        msg['To'] = recipient
        mailhost.send(msg.as_string())
Ejemplo n.º 21
0
 def getMultiAdapter(self, objects, interface, name=u''):
     adapter = self.adapters.queryMultiAdapter(objects, interface, name)
     if adapter is None:
         raise ComponentLookupError(objects, interface, name)
     return adapter
Ejemplo n.º 22
0
 def getUtility(self, provided, name=u''):
     utility = self.utilities.lookup((), provided, name)
     if utility is None:
         raise ComponentLookupError(provided, name)
     return utility
Ejemplo n.º 23
0
def send_distribution_list(obj, event):
    if not event.new_state.id in ['internally_published']:
        return
    #other
    all_email = list()
    report_authors = obj.report_author
    mission_members = get_mission(obj).mission_members
    mission_distribution = obj.mission_distribution

    #creator
    creator = obj.Creator()
    creator_info = obj.portal_membership.getMemberInfo(creator)
    creator_full_name = creator_info['fullname']

    for i in set(report_authors + mission_members + [creator]):
        email = obj.portal_membership.getMemberById(i).getProperty('email')
        all_email.append(email)

    all_email.extend(mission_distribution)
    filtered_email = list(set(all_email))

    converter = getUtility(IPDFConverter)
    pdf = converter.convert(obj)

    mailhost = obj.MailHost

    if not mailhost:
        raise ComponentLookupError('You must have a Mailhost utility to'
                                   'execute this action')

    from_address = obj.email_from_address
    if not from_address:
        raise ValueError('You must provide a source address for this'
                         'action or enter an email in the portal properties')
    from_name = obj.email_from_name
    source = "%s <%s>" % (from_name, from_address)

    event_title = safe_unicode(safe_unicode(obj.Title()))
    subject = event_title

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = source

    body = """You can view the full report online at:

    %(url)s

    --
    This is a system message from %(site_name)s.

    """ % {
        'url': obj.absolute_url(),
        'site_name': getSite().title
    }

    body_safe = body.encode('utf-8')
    htmlPart = MIMEText(body_safe, 'plain', 'utf-8')
    msg.attach(htmlPart)

    # generated pdf attachments

    attachment = MIMEBase('application', 'pdf')
    attachment.set_payload(pdf.buf)
    Encoders.encode_base64(attachment)
    attachment.add_header('Content-Disposition',
                          'attachment',
                          filename=subject + '.pdf')
    msg.attach(attachment)

    #attactments in the report
    file_brains = obj.getFolderContents()
    for file_brain in file_brains:
        file = file_brain.getObject().getFile()
        ctype = file.getContentType()
        filename = file.filename

        maintype, subtype = ctype.split(('/'), 1)
        attachment = MIMEBase(maintype, subtype)
        attachment.set_payload(str(file))
        Encoders.encode_base64(attachment)
        attachment.add_header('Content-Disposition',
                              'attachment',
                              filename=filename)
        msg.attach(attachment)

    #send email
    for recipient in filtered_email:
        # skip broken recipients
        if not recipient:
            continue
        if '@' not in recipient:
            continue

        del msg['To']
        msg['To'] = recipient
        mailhost.send(msg.as_string())
Ejemplo n.º 24
0
    def __init__(self, dsn, model=None, transactional=True, twophase=False,
                 engine_options={}, session_options={},
                 extension_options={}, **kw):
        """ 'dsn' - a RFC-1738-style connection string

            'model' - optional instance of model.Model

            'engine_options' - optional keyword arguments passed to
            create_engine()

            'session_options' - optional keyword arguments passed to
            create_session() or sessionmaker()

            'extension_options' - optional keyword argument passed to
            ZopeTransactionExtension()

            'transactional' - True|False, only used by SQLAlchemyDA,
                              *don't touch it*
        """

        self.dsn = dsn
        self.url = make_url(dsn)
        self.host = self.url.host
        self.port = self.url.port
        self.username = self.url.username
        self.password = self.url.password
        self.dbname = self.url.database
        self.twophase = twophase
        self.drivername = self.url.drivername
        self.transactional = transactional
        self.engine_options = engine_options
        if 'echo' in kw:
            self.engine_options.update(echo=kw['echo'])
        self.session_options = session_options
        self.extension_options = extension_options
        self._model = None
        self._createEngine()

        if model:

            if isinstance(model, Model):
                self._model = model

            elif isinstance(model, str):

                try:
                    util = getUtility(IModelProvider, model)
                except ComponentLookupError:
                    raise ComponentLookupError("No named utility '%s' providing IModelProvider found" % model)

                self._model = util.getModel(self.metadata)

            elif callable(model):
                self._model = model(self.metadata)

            else:
                raise ValueError("The 'model' parameter passed to constructor must either be "
                                 "the name of a named utility implementing IModelProvider or "
                                 "an instance of z3c.sqlalchemy.model.Model.")

            if not isinstance(self._model, Model):
                raise TypeError('_model is not an instance of model.Model')

        # mappers must be initialized at last since we need to acces
        # the 'model' from within the constructor of LazyMapperCollection
        self._mappers = LazyMapperCollection(self)
Ejemplo n.º 25
0
 def getSiteManager(self):
     if self._components is None:
         raise ComponentLookupError('No component registry defined.')
     return self._components
Ejemplo n.º 26
0
def getUtility(interface, name='', context=None):
    utility = queryUtility(interface, name, context=context)
    if utility is not None:
        return utility
    raise ComponentLookupError(interface, name)
Ejemplo n.º 27
0
def getDefaultViewName(object, request, context=None):
    name = queryDefaultViewName(object, request, context=context)
    if name is not None:
        return name
    raise ComponentLookupError("Couldn't find default view name", context,
                               request)
Ejemplo n.º 28
0
def getAdapter(object, interface=Interface, name=u'', context=None):
    adapter = queryAdapter(object, interface, name, None, context)
    if adapter is None:
        raise ComponentLookupError(object, interface, name)
    return adapter