Esempio n. 1
0
class IMustReadSettings(Interface):
    '''registry settings
    '''

    expired_recipient = schema.List(
        title=_(u'label_expired-recipient', default=u'Expired recipient'),
        description=_(
            u'help_expired-recipient',
            default=(
                u'Email address(es) the expired notifications are sent to '
                u"If not given, the portal's admin address is used")),
        value_type=schema.TextLine(),
        required=False,
        default=[],
    )

    expired_force_deadline = schema.Bool(
        title=_(u'label_expired-deadline',
                default=u'Force Deadline for expiration mails'),
        description=_(
            u'help_expired-deadline',
            default=(u'If set to true, users that read an item after their '
                     u'deadline get included in the email report')),
        default=True,
    )
class MustReadEditForm(EditForm):
    """
    An edit form for the mail action
    """
    form_fields = form.FormFields(IMustReadAction)
    label = _(u'title_editform', default=u"Edit MustRead Action")
    description = form_description
    form_name = _p(u"Configure element")
    def summary(self):

        if self.reminder_message is None or (
                not self.reminder_message.strip()):
            return _(
                u'rule_description_noreminder',
                default=(
                    u"Request confirmation for users with role '${role}' "
                    u"on the object (deadline today + ${days} days, "
                    u"no reminder)"),
                mapping=dict(role=self.role,
                             days=self.deadline))
        return _(
            u'rule_description',
            default=(
                u"Request confirmation for users with role '${role}' on "
                u"the object (deadline today + ${days} days, reminder "
                u"${reminder} days before deadline)"),
            mapping=dict(role=self.role,
                         days=self.deadline,
                         reminder=self.reminder_delay))
class MustReadAddForm(AddForm):
    """
    An add form for the mail action
    """
    form_fields = form.FormFields(IMustReadAction)
    label = _(u'title_addform', default=u"Add MustRead Action")
    description = form_description
    form_name = _p(u"Configure element")

    def create(self, data):
        a = MustReadAction()
        form.applyChanges(a, self.form_fields, data)
        return a
Esempio n. 5
0
    def __call__(self):
        tracker = getUtility(ITracker)
        notified = []
        for obj in tracker.what_to_read(context=self.context):
            event.notify(ReadReminderEvent(obj))
            notified.append('/'.join(obj.getPhysicalPath()))

        if notified:
            api.portal.show_message(
                _(u'msg_reminder_fired',
                  default=(
                      u'Reminder event fired for ${count} objects: ${objects}'
                  ),
                  mapping={
                      'count': len(notified),
                      'objects': ', '.join(notified)
                  }), self.request, 'info')
        else:
            api.portal.show_message(
                _(u'msg_no_reminder_fired',
                  default=u'No reminder event fired'), self.request, 'info')

        self.do_redirect()
    def __call__(self):
        obj = self.event.object
        now = datetime.utcnow()
        deadline = now + timedelta(days=self.element.deadline)

        users = self.affected_users

        tracker = getUtility(ITracker)
        current_user = api.user.get_current().id
        new_users = tracker.schedule_must_read(obj, users, deadline,
                                               current_user)

        logger.info((
            'scheduled mustread on {path}, deadline '
            '{deadline:%Y-%m-%d %H:%M:%S} '
            'for {usercount} users: {users}').format(
                path='/'.join(obj.getPhysicalPath()),
                deadline=deadline,
                usercount=len(new_users),
                users=', '.join(new_users))
        )

        self._send_mail(new_users,
                        self.element.notification_subject,
                        self.element.notification_message)

        api.portal.show_message(_(
            u'msg-confirmation-requested',
            default=(
                u'Read confirmation requested by ${deadline} for ${count} '
                'users: ${userlist}'),
            mapping=dict(
                count=len(new_users),
                deadline=api.portal.get_localized_time(deadline, True),
                userlist=', '.join(new_users))),
            self.context.REQUEST,
            'info')
class IMustReadAction(Interface):
    """Definition of the configuration available for a mustread action
    """

    source = schema.TextLine(
        title=_p(u'Email source'),
        description=_p(
            ('The email address that sends the email. If no email is '
             'provided here, it will use the portal from address.')),
        required=False)

    role = schema.Choice(
        title=_(u'field_role_title', default=u"Role"),
        description=_(
            u'field_role_description',
            default=(
                u"Select a role. The action will look up the all Plone site "
                u"users who explicitly have this role (also via groups) on the"
                u" object and send a message to their email address.")),
        vocabulary='collective.contentrules.mailtorole.roles',
        required=True)

    acquired = schema.Bool(
        title=_(u'field_acquired_title', default=u"Acquired Roles"),
        description=_(
            u'field_acquired_description',
            default=(
                u"Should users that have this role as an acquired role "
                u"also receive this email?")),
        required=False,
        default=config.DEFAULT_ACQUIRED_ROLES)

    global_roles = schema.Bool(
        title=_(u'field_global_roles_title', default=u"Global Roles"),
        description=_(
            u'field_global_roles_description',
            default=(
                u"Should users that have this role as a role in the "
                u"whole site also receive this email?")),
        required=False)

    notification_subject = schema.TextLine(
        title=_(u"Notification Subject"),
        description=_p(u"Subject of the message"),
        required=True,
        default=config.DEFAULT_NOTIFICATION_SUBJECT)

    notification_message = schema.Text(
        title=_(u"Notification Message"),
        description=_(
            u'field_message_description',
            default=(
                u"Type in here the message that you want to mail. Some "
                u"defined content can be replaced: ${title} will be replaced "
                u"by the title of the newly created item. ${url} will be "
                u"replaced by the URL of the newly created item.")),
        required=True,
        default=config.DEFAULT_NOTIFICATION_TEXT)

    reminder_subject = schema.TextLine(
        title=_(u"Reminder Subject"),
        description=_p(u"Subject of the message"),
        required=True,
        default=config.DEFAULT_REMINDER_SUBJECT)

    reminder_message = schema.Text(
        title=_(u"Reminder Message"),
        description=_(
            u'field_message_reminder_description',
            default=(
                u""
                u"leave empty to not send a reminder message")),
        required=False,
        default=config.DEFAULT_REMINDER_TEXT)

    deadline = schema.Int(
        title=_(u'label_deadline', default=u"Deadline Delay"),
        description=_(
            u'help_deadline',
            default=(
                u"Number of days a read requests must be confirmed within. "
                u"Will be used to compute the deadline of requests.")),
        required=True,
        default=config.DEFAULT_DEADLINE_DELAY
        )

    reminder_delay = schema.Int(
        title=_(u'label_reminder-delay', default=u"Reminder Delay"),
        description=_(
            u'help_reminder-delay',
            default=(
                u"Defines how many days before the deadline a "
                u"reminder email will be sent")),
        required=True,
        default=config.DEFAULT_REMINDER_DELAY
        )
        if too_early:
            logger.info((
                u'too early to remind {count} users for {path}: '
                u'{userlist}').format(
                    count=len(too_early), path=path,
                    userlist=', '.join([
                        '{0}({1:%Y-%m-%d})'.format(*u) for u in too_early])
                    ))

        self._send_mail(remind_today, self.element.reminder_subject,
                        self.element.reminder_message)


form_description = _(
    u'form_description',
    default=(
        u"An action action that requests a read-confirmation from users who "
        u"have a role on the object")
    )


class MustReadAddForm(AddForm):
    """
    An add form for the mail action
    """
    form_fields = form.FormFields(IMustReadAction)
    label = _(u'title_addform', default=u"Add MustRead Action")
    description = form_description
    form_name = _p(u"Configure element")

    def create(self, data):
        a = MustReadAction()
Esempio n. 9
0
    def __call__(self):
        path = '/'.join(self.context.getPhysicalPath())
        logger.warn('processing expired notifications for context ' + path)
        tracker = getUtility(ITracker)

        force_deadline = api.portal.get_registry_record(
            'expired_force_deadline', IMustReadSettings, True)

        items = tracker.what_to_read(context=self.context,
                                     force_deadline=force_deadline)
        data = []
        today_12_pm = datetime.datetime.combine(datetime.datetime.utcnow(),
                                                datetime.time.max)
        for item in items:
            path = '/'.join(item.getPhysicalPath())
            users = tracker.who_did_not_read(item,
                                             force_deadline=force_deadline,
                                             deadline_before=today_12_pm)

            if not users:
                # skip this item if there are no expired deadlines
                continue
            info = dict(item=item, users=[])
            for userid, deadline in users.iteritems():
                user = api.user.get(userid)
                if user is None:
                    logger.warn('user does not exist anymore: ' + userid)
                    fullname = userid
                    email = 'user has been deleted'
                else:
                    fullname = user.getProperty('fullname', userid)
                    email = user.getProperty('email')
                info['users'].append(
                    dict(name=fullname,
                         email=email,
                         deadline=api.portal.get_localized_time(
                             deadline, True)))
            data.append(info)
        if len(data) == 0:
            # nothing to do
            logger.info(
                (u'no open read requests ending before '
                 '{0:%Y-%m-%d %h:%M} for {1}').format(today_12_pm, path))
            return u'no open requests, no report sent'

        mail_text = self.template(self.context, self.request, data=data)
        portal = api.portal.get()
        email_charset = portal.getProperty('email_charset')
        mailhost = api.portal.get_tool('MailHost')
        from_address = portal.getProperty('email_from_address')
        recipient = api.portal.get_registry_record('expired_recipient',
                                                   IMustReadSettings, [])
        if not recipient:
            recipient = from_address

        subject = self.SUBJECT
        if isinstance(subject, Message):
            subject = translate(subject, context=self.request)

        logger.info(u'Sending expired notification to {0}:\n{1}\n'.format(
            safe_unicode(recipient), safe_unicode(mail_text)))
        mailhost.send(messageText=mail_text,
                      mto=recipient,
                      mfrom=from_address,
                      subject=subject,
                      charset=email_charset)

        msg = _(u'The following report has been sent to ${email}:',
                mapping=dict(email=recipient))
        return u'{0}:\n\n:{1}'.format(translate(msg), mail_text)