source: products/qPloneComments/branches/jcbrand-abuseFeature/utils.py @ 1161

Last change on this file since 1161 was 1161, checked in by jcbrand, 15 years ago

Log email errors, so that the report abuse form still closes

  • Property svn:eol-style set to native
File size: 8.5 KB
RevLine 
[1161]1import logging
2import smtplib
[108]3from Products.CMFPlone import MessageFactory
[1]4from Products.CMFCore.utils import getToolByName
[1161]5from Products.CMFPlone import PloneMessageFactory as _
[108]6
[1161]7log = logging.getLogger('Products.qPloneComments.utils.py')
8
[1]9# Get apropriate property from (propery_sheeet) configlet
10def getProp(self, prop_name, marker=None):
11    result = marker
12    pp = getToolByName(self, 'portal_properties')
13    config_ps = getattr(pp, 'qPloneComments', None)
14    if config_ps:
15        result =  getattr(config_ps, prop_name, marker)
16    return result
17
18def publishDiscussion(self):
19    roles = ['Anonymous']
20    self.review_state = "published"
21    self.manage_permission('View', roles, acquire=1)
22    self._p_changed = 1
23    self.reindexObject()
24
25def setAnonymCommenting(context, allow=False):
26    portal = getToolByName(context, 'portal_url').getPortalObject()
27    if allow:
28        portal.manage_permission('Reply to item', ['Anonymous','Manager','Member'], 1)
29    else:
30        portal.manage_permission('Reply to item', ['Manager','Member'], 1)
31
32def manage_mails(reply, context, action):
33    def sendMails(props, actions, key):
34        for p in props:
35            if p in actions[key]:
36                send_email(reply, context, p)
37
38    prop_sheet = context.portal_properties['qPloneComments']
39    props = filter(lambda x: prop_sheet.getProperty(x), prop_sheet.propertyIds())
40
41    actions = { 'onPublish': ('enable_approve_user_notification',
42                              'enable_reply_user_notification',
43                              'enable_published_notification'),
44                'onDelete' :  ('enable_rejected_user_notification',),
[918]45                'onApprove': ('enable_approve_notification',),
[943]46                'onAnonymousReportAbuse': ('enable_anonymous_report_abuse',),
47                'onAuthenticatedReportAbuse': ('enable_authenticated_report_abuse')}
[1]48
49    if action == 'publishing':
50        sendMails(props, actions, 'onPublish')
51
52    elif action == 'deleting':
53        sendMails(props, actions, 'onDelete')
54
55    elif action == 'aproving':
56        sendMails(props, actions, 'onApprove')
57
[918]58    elif action == 'report_abuse':
[943]59        pm = getToolByName(context, 'portal_membership')
60        if pm.isAnonymousUser():
61            sendMails(props, actions, 'onAnonymousReportAbuse')
62        else:
63            sendMails(props, actions, 'onAuthenticatedReportAbuse')
[918]64
[1]65def getMsg(context, template, args):
66    return getattr(context, template)(**args)
67
68def allowEmail(context, reply, state, creator):
69    condition = getattr(context, 'emailCommentNotification', True)
70    if callable(condition):
71        condition = condition(reply=reply, state=state, creator=creator)
72    return condition
73
74def send_email(reply, context, state):
75    def getEmail(obj, context):
76        email = obj.getProperty('email', None)
77        if email is None:
78            creators = hasattr(obj, 'listCreators') and obj.listCreators() or [obj.Creator(),]
79            userid = creators and creators[0] or ""
80            creator = getToolByName(context, 'portal_membership').getMemberById(userid)
81            if creator and allowEmail(context, reply, state, creator):
82                return creator.getProperty('email', '')
83        else:
84            return email
85        return ''
86
87    def getParent(reply):
[108]88        if reply.meta_type == 'Discussion Item':
89            reply = reply.inReplyTo()
90            return getParent(reply)
91        return reply
[1]92
93    def getDIParent(reply):
94        r = reply.inReplyTo()
95        return r.meta_type == 'Discussion Item' and r or None
96
97    def getParentOwnerEmail(reply, context):
98        creator_id = getParent(reply).getOwnerTuple()[1]
99        creator = getToolByName(context, 'portal_membership').getMemberById(creator_id)
100        if creator and allowEmail(context, reply, state, creator):
101            return creator.getProperty('email', '')
102        return ''
103
104    args = {}
105    if reply:
106        user_email = getEmail(reply, context)
107        reply_parent = getParent(reply)
108
109    organization_name = getProp(context, 'email_subject_prefix', '')
110    creator_name = reply.getOwnerTuple()[1]
111    admin_email = context.portal_url.getPortalObject().getProperty('email_from_address')
112
[81]113    subject = ''
[1]114    if state == 'enable_approve_user_notification':
[108]115        subject = 'Your comment on "%s" is now published' % getParent(context).Title()
[1]116        if user_email:
117            template = 'notify_comment_template'
118            args={'mto': user_email,
119                  'mfrom': admin_email,
120                  'obj': reply_parent,
121                  'organization_name': organization_name,
122                  'name': creator_name}
123        else:
124            args = {}
125
126    elif state == 'enable_rejected_user_notification':
[108]127        subject = 'Your comment on "%s" was not approved' % getParent(context).Title()
[1]128        if user_email:
129            template = 'rejected_comment_template'
130            args={'mto': user_email,
131                  'mfrom': admin_email,
132                  'obj': reply_parent,
133                  'organization_name': organization_name,
134                  'name': creator_name}
135        else:
136            args = {}
137
138    elif state == 'enable_reply_user_notification':
139        template = 'reply_notify_template'
[108]140        subject = 'Someone replied to your comment on "%s"' % getParent(context).Title()
[1]141        di_parrent = getDIParent(reply)
142        if di_parrent:
143            user_email = getEmail(di_parrent, context)
144            if user_email:
145                args={'mto': user_email,
146                      'mfrom': admin_email,
147                      'obj': reply_parent,
148                      'organization_name': organization_name,
149                      'name': di_parrent.getOwnerTuple()[1]}
150            else:
151                args = {}
152        else:
153            args = {}
154
155    elif state == 'enable_published_notification':
156        template = 'published_comment_template'
157        user_email = getParentOwnerEmail(reply, context)
158        if user_email:
159            args={'mto':user_email,
160                  'mfrom':admin_email,
161                  'obj':reply_parent,
162                  'organization_name':organization_name}
[108]163            subject = '[%s] New comment added' % organization_name
[1]164        else:
165            args = {}
166
167    elif state == 'enable_approve_notification':
168        template = 'approve_comment_template'
169        user_email = getProp(context, "email_discussion_manager", None)
170        if user_email:
171            args={'mto':user_email,
172                  'mfrom':admin_email,
173                  'obj':reply_parent,
174                  'organization_name':organization_name}
[108]175            subject = '[%s] New comment awaits moderation' % organization_name
[1]176        else:
177            args = {}
178
[940]179    elif state in ('enable_authenticated_report_abuse', 'enable_anonymous_report_abuse'):
[929]180        template = 'report_abuse_template'
[918]181        user_email = getProp(context, "email_discussion_manager", None)
182        if user_email:
[940]183            message = context.REQUEST.get('message')
184            comment_id = context.REQUEST.get('comment_id')
[918]185            pd = context.portal_discussion
186            dl = pd.getDiscussionFor(context)
187            comment = dl._container.get(comment_id)
188            args = {'mto': user_email,
189                    'mfrom': admin_email,
190                    'obj': reply_parent,
191                    'message':message,
192                    'organization_name': organization_name,
193                    'name': creator_name,
194                    'comment_id':comment_id,
195                    'comment_desc':comment.description,
196                    'comment_text':comment.text
197                    }
198            subject = '[%s] A comment on "%s" has been reported for abuse.' \
199                            % (organization_name, getParent(context).Title())
200        else:
201            args = {}
202
[1]203    if args:
204        msg = getMsg(context, template, args)
[81]205        p_utils = context.plone_utils
206        site_props = context.portal_properties.site_properties
207        host = p_utils.getMailHost()
[1161]208        try:
209            host.secureSend(msg, user_email, admin_email,
210                            subject = subject,
211                            subtype = 'plain',
212                            debug = False,
213                            charset = site_props.getProperty('default_charset', 'utf-8'),
214                            From = admin_email)
215        except smtplib.SMTPRecipientsRefused:
216            log.error(_('SMTPRecipientsRefused: Could not send the email'
217            'notification. Have you configured an email server for Plone?'))
218           
[1]219
[1161]220
[1]221def setStatusMsg(state, context, msg):
[800]222    context.plone_utils.addPortalMessage(msg)
[929]223
Note: See TracBrowser for help on using the repository browser.