Пример #1
0
class SubscribeNewsletterForm(Form):

    fields = Fields(ISubscribeNewsletterForm)
    ignoreContext = True
    label = _(u"")

    def __init__(self, context, request, data=None):
        """
        """
        super(Form, self).__init__(context, request)
        self.data = data

    def newslettertheme(self):
        """Returns brain of NewsletterTheme."""
        path = self.data.newsletters
        query = {
            'object_provides': INewsletterTheme.__identifier__,
        }
        if path:
            portal_state = getMultiAdapter((self.context, self.request),
                                           name="plone_portal_state")
            path = '{0}{1}'.format(portal_state.navigation_root_path(), path)
            query.update({'path': {
                'depth': 0,
                'query': path,
            }})
        catalog = getToolByName(self.context, 'portal_catalog')
        brains = catalog(query)
        if brains:
            return brains[0]

    def updateWidgets(self):
        super(self.__class__, self).updateWidgets()

        self.widgets['email'].size = 20
        newslettertheme = self.newslettertheme()
        self.widgets['format'].field.default = newslettertheme.getObject(
        ).default_format

    @property
    def action(self):
        """ Rewrite HTTP POST action.

        If the form is rendered embedded on the others pages we
        make sure the form is posted through the same view always,
        instead of making HTTP POST to the page where the form was rendered.
        """
        path = self.newslettertheme().getPath()
        return '{0}/@@register-newsletter?path={1}'.format(
            self.context.absolute_url(), path)

    @button.buttonAndHandler(_('Subscribe'), name='subscribe')
    def search(self, action):
        """ Form button hander. """

        data, errors = self.extractData()

        if not errors:
            pass
Пример #2
0
class AddForm(base.AddForm):

    form_fields = form.Fields(ISubscribeNewsletterPortlet)
    label = _(u"Add Subscribe Newsletter Portlet")
    description = _(u"This portlet displays Subscribe Newsletter Portlet.")

    def __init__(self, context, request):
        super(AddForm, self).__init__(context, request)

    def create(self, data):
        return Assignment(**data)
Пример #3
0
class ISubscribeNewsletterPortlet(IPortletDataProvider):
    """A portlet displaying a subscribe newsletters.
    """

    name = TextLine(
        title=_(u"Name of Portlet"),
        default=u"",
        required=False,
    )

    newsletters = schema.Choice(
        title=_(u"Newsletters"),
        description=_(u"Find the newsletter theme."),
        required=False,
        source=SearchableTextSourceBinder(
            {'object_provides': INewsletterTheme.__identifier__},
            default_query='path:',
        ),
    )
Пример #4
0
    def __call__(self, ):
        base_url = "%s/subscribers_infos" % self.context.absolute_url()
        if "SUBMIT" not in self.request.form:
            return super(ManageBouncedSubscribers, self).__call__()

        count = self.context.remove_subscribers()
        tool = getToolByName(self.context, 'plone_utils')
        tool.addPortalMessage(
            _("removed_x_subscribers",
              default="Removed ${no} subscribers",
              mapping={'no': count}))
        return self.request.response.redirect(base_url)
Пример #5
0
    def __call__(self,):
        base_url = "%s/subscribers_infos" % self.context.absolute_url()
        if "SUBMIT" not in self.request.form:
            return super(ManageBouncedSubscribers, self).__call__()

        count = self.context.remove_subscribers()
        tool = getToolByName(self.context, 'plone_utils')
        tool.addPortalMessage(_("removed_x_subscribers", 
                                default="Removed ${no} subscribers",
                                mapping={'no':count}
                                ))
        return self.request.response.redirect(base_url)
Пример #6
0
class ISubscribeNewsletterForm(Schema):

    email = TextLine(
        title=_(u"E-mail address"),
        required=True,
    )

    gdpr = schema.Bool(
        title=_('Activer l\'abonnement'),
        description=
        _(u'En cochant la case, vous acceptez que les informations que vous fournissez soient trait&eacute;es conformément &agrave; notre <a href="gdpr-view">politique de confidentialit&eacute;</a>'
          ),
        default=False,
        required=True)

    format = Choice(
        title=_(u"Format"),
        required=True,
        vocabulary=formats,
    )

    title = TextLine(required=False, )

    message = Text(required=False, )
Пример #7
0
    def _post_init(self):
        """Post-init method (that is, method that is called AFTER the class has been set into the ZODB)
        """
        self.activationMailSubject = translate(_("Please activate your newsletter account"), context=self.REQUEST)
        self.activationMailTemplate = translate(_('default_activation_mail_template',
                                                  default=u"""Dear subscriber,

We have received and recorded your newsletter subscription.
You must now activate your account to receive our newsletters.
To do this, just browse to this URL...
%(url)s
Then you'll receive our next newsletters at %(email)s

PLEASE DON'T REPLY TO THIS MAIL"""), context=self.REQUEST)
        self.newsletterFooter = translate(_('default_newsletter_footer',
                                            default=u"""Thank you for subscribing to this newsletter.<br />
You can <a href="%(url)s">change your preferences</a> at any time.
"""), context=self.REQUEST)
        self.invokeFactory('NewsletterBTree', 'subscribers',
                           title=translate(_('Subscribers'), context=self.REQUEST))
        getattr(self, 'subscribers').indexObject()
        self.indexObject()
        self._initCatalog()
        return
Пример #8
0
 def checkTalExpressions(self, talExpressions, state=None, errors=None):
     """
     Check TALES expressions for edit_form validation
     """
     talEngine = Expressions.getEngine()
     for fieldId, value in talExpressions:
         if not value:
             continue
         try:
             dummy = talEngine.compile(value)
         except CompilerError, e:
             msg = _('TALES compilation error: ${error}', mapping={'error':str(e)})
             if state is not None:
                 state.setError(fieldId, msg)
             if errors is not None:
                 errors[fieldId] = msg
Пример #9
0
    def unSubscribe(self, subscriber_id, REQUEST=None):
        """The subscriber clicked the Unsubscribe button
        """
        subscriber = self.getSubscriberById(subscriber_id)
        mtool = getToolByName(self, 'portal_membership')
        checkPermission = mtool.checkPermission
        can_access_theme = checkPermission(permissions.View, self)
        newSecurityManager(REQUEST, ownerOfObject(self))
        if subscriber is not None:
            parent = subscriber.aq_parent
            parent.manage_delObjects([subscriber_id,])

        if REQUEST is not None:
            # Check if we have access to the newsletter theme
            if can_access_theme:
                REQUEST.RESPONSE.redirect(self.absolute_url() + '/NewsletterTheme_unsubscribed')
            else:
                portal_url = getToolByName(self, 'portal_url')()
                plone_utils = getToolByName(self, 'plone_utils')
                plone_utils.addPortalMessage(_('unsubscribe_success_message',
                                               default=u"You have been successfully unsubscribed from this newsletter."))
                REQUEST.RESPONSE.redirect(portal_url)
        return
Пример #10
0
    def title(self):
        return self.name or _(u'Our newsletter')


class PortletFormView(FormWrapper):
    """ Form view which renders z3c.forms embedded in a portlet.

    Subclass FormWrapper so that we can use custom frame template. """

    index = ViewPageTemplateFile("formwrapper.pt")


formats = SimpleVocabulary(
    [
        SimpleTerm(
            title=_(u"HTML"),
            value=u"HTML",
        ),
        SimpleTerm(
            title=_(u"Text"),
            value=u"Text",
        ),
    ]
)


class ISubscribeNewsletterForm(Schema):

    email = TextLine(
        title=_(u"E-mail address"),
        required=True,
Пример #11
0
    def subscribeFormProcess(self, REQUEST=None):
        """Handles NewsletterTheme_subscribeForm"""

        if REQUEST is None:
            REQUEST = self.REQUEST
        errors = {}
        data = {}
        charset = self.ploneCharset()

        if REQUEST.form.has_key('email'):
            # Form submitted
            emailaddress = REQUEST.form.get('email', '').strip()
            data['email'] = emailaddress

            email_verify = REQUEST.form.get('email_verify', 'not_submitted')

            format = REQUEST.form.get('format', self.default_format)
            data['format'] = format

            if not self.checkMailAddress(emailaddress):
                errors['email'] = _('This is not a valid mail address')
                return data, errors

             # This is an automated request, probably a bot, we fake a succesful registration"
            if email_verify:
                data['success'] = 1
                return data, errors

            if self.alreadySubscriber(emailaddress):
                errors['email'] = _('There is already a subscriber with this address')
            if not errors:
                # Creating the new account
                self._subscribersCount += 1
                newId = self._getRandomIdForSubscriber()
                # Continue method as owner of this object for "invokeFactory" security checkings.
                # (creating new objects through invokeFactory is not possible as anonymous because an owner is required)
                oldSecurityManager = getSecurityManager()
                newSecurityManager(REQUEST, SpecialUsers.system)
                newSubscriber = self.createSubscriberObject(newId)
                newSubscriber.edit(format=format, active=0, email=emailaddress)
                setSecurityManager(oldSecurityManager)

                # Make URL for editing this object
                subscriberEditUrl = newSubscriber.absolute_url() + '/Subscriber_editForm'   # :( FIXME
                #actions_tool = getToolByName(self, 'portal_actions')
                #actions = actions_tool.listFilteredActionsFor(object=newSubscriber)
                #subscriberEditUrl = [action['url'] for action in actions['object']
                #                     if action['id'] == 'edit'][0]

                # Make and send the activation mail
                """
                mailBody = ("From: %s\r\n"
                            "To: %s\r\n"
                            "Content-Type: text/plain; charset=%s\r\n"
                            "Subject: %s\r\n\r\n")
                mailBody = mailBody % (self.authorEmail, data['email'],
                                       self.ploneCharset(), self.activationMailSubject)
                #mailBody += self.activationMailTemplate % {'url': self.absolute_url() + '?active=%s&format=%s' % (newId, format), 'email': emailaddress}
                mailBody += self.activationMailTemplate % {'url': self.id + '?active=%s&format=%s' % (newId, format), 'email': emailaddress}

                """
                mailMsg=email.Message.Message()
                mailMsg["To"]=data['email']
                mailMsg["From"]=self.authorEmail
                mailMsg["Subject"]=str(Header(safe_unicode(self.activationMailSubject), 'utf8'))
                mailMsg["Date"]=email.Utils.formatdate(localtime=1)
                mailMsg["Message-ID"]=email.Utils.make_msgid()
                mailMsg["Mime-version"]="1.0"

                bodyText = self.activationMailTemplate % {'url': self.id + '?active=%s&format=%s' % (newId, format), 'email': emailaddress}
                mailMsg["Content-type"]="text/plain"
                mailMsg.set_payload(safe_unicode(bodyText).encode(charset), charset)
                #mailMsg.preamble="Mime message\n"
                mailMsg.epilogue="\n" # To ensure that message ends with newline

                try:
                    #TODO: is
                    self.sendmail(self.authorEmail, (emailaddress,), mailMsg, subject = mailMsg['subject'])
                except Exception, e:
                    raise
                    # The email could not be sent, probably the specified address doesn't exist
                    #errors['email'] = translate('Email could not be sent. Error message is: ${error}', mapping={'error':str(e)}, context=self)
                    #data['email'] = emailaddress
                    #data['format'] = self.default_format
                    #transaction.abort()
                    #return data, errors

                if self.notify:
                    # Notify the NewsletterTheme owner
                    """mailBody = ("From: %s\r\n"
                                "To: %s\r\n"
                                "Content-Type: text/plain; charset=%s\r\n"
                                "Subject: %s : %s\r\n\r\n"
                                "%s\n%s")
                    mailBody = mailBody % (self.authorEmail, self.testEmail,
                                           self.ploneCharset(),
                                           self.title,
                                           translate("Newsletter new subscriber", domain='plonegazette', context=REQUEST),
                                           translate("See the new account at...", domain='plonegazette', context=REQUEST),
                                           subscriberEditUrl)
                    subject = "Subject: %s : %s" % (self.title,
                                           translate("Newsletter new subscriber", domain='plonegazette', context=REQUEST))
                    """
                    subject = "%s : %s" % (self.title,
                                           translate("Newsletter new subscriber", domain='plonegazette', context=REQUEST))
                    mailMsg=email.Message.Message()
                    mailMsg["To"]=self.testEmail
                    mailMsg["From"]=self.authorEmail
                    mailMsg["Subject"]=str(Header(safe_unicode(subject), 'utf8'))
                    mailMsg["Date"]=email.Utils.formatdate(localtime=1)
                    mailMsg["Message-ID"]=email.Utils.make_msgid()
                    mailMsg["Mime-version"]="1.0"

                    bodyText = "%s\n%s\n%s%s" % (translate("See the new account at...", context=REQUEST, domain='plonegazette'),
                                           subscriberEditUrl, 'E-mail address: ', data['email'])
                    mailMsg["Content-type"]="text/plain"
                    #mailMsg.set_charset(charset)
                    mailMsg.set_payload(safe_unicode(bodyText).encode(charset), charset)
                    #mailMsg.preamble="Mime message\n"
                    mailMsg.epilogue="\n" # To ensure that message ends with newline

                    self.sendmail(self.authorEmail, (self.testEmail,), mailMsg, subject = mailMsg['subject'])
                data['success'] = 1
Пример #12
0
    def createSubscribersFromCSV(self, file_upload):
        """
        Create all subscribers objects from csv file uploaded
        """

        # Reset old log
        self._csv_import_log = ''

        filename = file_upload.filename
        filedatas = file_upload.read()
        var_directory = self.Control_Panel.getCLIENT_HOME()

        dialect = csv.excel

        # first, create a temp file on file system
        self._createTempFile(var_directory, filename, filedatas)

        # open temp csv file
        reader = csv.DictReader(open('%s/%s' % (var_directory, filename)), ['email', 'active', 'format'], dialect=dialect)

        # get target folder for subscribers object, or create it if not exist
        subscriber_folder = self.getSubscriberFolder()
        if subscriber_folder is None:
            self.invokeFactory('NewsletterBTree', 'subscribers')
            self.subscriber_folder_id = 'subscribers'
            subscriber_folder = getattr(self, 'subscribers')

        # remove headers
        first_row = reader.next()
        if first_row['email']!='email':
            return _('csv_headers_error',
                     default=u"You must add headers to the csv file : email, active, format ('email' at least)")

        # for each row, create a subscriber object
        default_format = self.default_format
        k = 0
        already_used = []
        not_valid = []
        for row in reader:

            # get the field value, or the default value
            if row['active']=='1':
                active = True
            elif row['active']=='0':
                active = False
            else:
                active = False

            if row['format']:
                if row['format'].lower()=='html':
                    format = 'HTML'
                elif row['format'].lower()=='text':
                    format = 'Text'
                else:
                    format = default_format
            else:
                format = default_format

            email = row['email']
            email = email.strip()

            # check mail address validity
            if not checkMailAddress(self,email):
                not_valid.append(email)
            else:

                # check if subscriber already exist
                if self.alreadySubscriber(email):
                    already_used.append(email)
                else:
                    newId = self._getRandomIdForSubscriber()
                    subscriber = self.createSubscriberObject(newId)

                    subscriber.edit(format=format, active=active, email=email)
                    k += 1
                    self._subscribersCount += 1

        # remove temp csv file
        os.remove('%s/%s' % (var_directory, filename))

        self._logCSVImportResult(not_valid, already_used)

        msg = _('csv_import_report',
                default=u"""${count_created} subscribers created.
${count_already_there} users were already subscriber on this newsletter theme.
${count_not_valid} emails were not valid.""",
                mapping={'count_created': k,
                         'count_already_there': len(already_used),
                         'count_not_valid': len(not_valid)})
        return msg
Пример #13
0
 def title(self):
     return self.name or _(u'Our newsletter')
Пример #14
0
 def title(self):
     return self.name or _(u'Our newsletter')
Пример #15
0
class EditForm(base.EditForm):
    form_fields = form.Fields(ISubscribeNewsletterPortlet)
    label = _(u"Edit Subscribe Newsletter Portlet")
    description = _(u"This portlet displays Subscribe Newsletter Portlet.")
Пример #16
0
class INewsletterTheme(Interface):
    """ Base content object for newsletters and subscribers """

    extra_filters = Text(title=_("IMAP bouncing detection filters"),
                         default=u"",
                         required=False)
Пример #17
0
    def title(self):
        return self.name or _(u'Our newsletter')


class PortletFormView(FormWrapper):
    """ Form view which renders z3c.forms embedded in a portlet.

    Subclass FormWrapper so that we can use custom frame template. """

    index = ViewPageTemplateFile("formwrapper.pt")


formats = SimpleVocabulary([
    SimpleTerm(
        title=_(u"HTML"),
        value=u"HTML",
    ),
    SimpleTerm(
        title=_(u"Text"),
        value=u"Text",
    ),
])


class ISubscribeNewsletterForm(Schema):

    email = TextLine(
        title=_(u"E-mail address"),
        required=True,
    )