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

Last change on this file since 1591 was 1356, checked in by jcbrand, 14 years ago

Show users full name in emails

  • Property svn:eol-style set to native
File size: 8.6 KB
Line 
1import logging
2import smtplib
3from Products.CMFPlone import MessageFactory
4from Products.CMFCore.utils import getToolByName
5from Products.CMFPlone import PloneMessageFactory as _
6
7log = logging.getLogger('Products.qPloneComments.utils.py')
8
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',),
45                'onApprove': ('enable_approve_notification',),
46                'onAnonymousReportAbuse': ('enable_anonymous_report_abuse',),
47                'onAuthenticatedReportAbuse': ('enable_authenticated_report_abuse')}
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
58    elif action == 'report_abuse':
59        pm = getToolByName(context, 'portal_membership')
60        if pm.isAnonymousUser():
61            sendMails(props, actions, 'onAnonymousReportAbuse')
62        else:
63            sendMails(props, actions, 'onAuthenticatedReportAbuse')
64
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    mtool = getToolByName(context, 'portal_membership')
76    def getEmail(obj, context):
77        email = obj.getProperty('email', None)
78        if email is None:
79            creators = hasattr(obj, 'listCreators') and obj.listCreators() or [obj.Creator(),]
80            userid = creators and creators[0] or ""
81            creator = mtool.getMemberById(userid)
82            if creator and allowEmail(context, reply, state, creator):
83                return creator.getProperty('email', '')
84        else:
85            return email
86        return ''
87
88    def getParent(reply):
89        if reply.meta_type == 'Discussion Item':
90            reply = reply.inReplyTo()
91            return getParent(reply)
92        return reply
93
94    def getDIParent(reply):
95        r = reply.inReplyTo()
96        return r.meta_type == 'Discussion Item' and r or None
97
98    def getParentOwnerEmail(reply, context):
99        creator_id = getParent(reply).getOwnerTuple()[1]
100        creator = mtool.getMemberById(creator_id)
101        if creator and allowEmail(context, reply, state, creator):
102            return creator.getProperty('email', '')
103        return ''
104
105    args = {}
106    if reply:
107        user_email = getEmail(reply, context)
108        reply_parent = getParent(reply)
109
110    organization_name = getProp(context, 'email_subject_prefix', '')
111    creator_name = reply.getOwnerTuple()[1]
112    creator = mtool.getMemberById(creator_name)
113    if creator is not None:
114        creator_name = creator.getProperty('fullname', creator_name)
115    admin_email = context.portal_url.getPortalObject().getProperty('email_from_address')
116
117    subject = ''
118    if state == 'enable_approve_user_notification':
119        subject = 'Your comment on "%s" is now published' % getParent(context).Title()
120        if user_email:
121            template = 'notify_comment_template'
122            args={'mto': user_email,
123                  'mfrom': admin_email,
124                  'obj': reply_parent,
125                  'organization_name': organization_name,
126                  'name': creator_name}
127        else:
128            args = {}
129
130    elif state == 'enable_rejected_user_notification':
131        subject = 'Your comment on "%s" was not approved' % getParent(context).Title()
132        if user_email:
133            template = 'rejected_comment_template'
134            args={'mto': user_email,
135                  'mfrom': admin_email,
136                  'obj': reply_parent,
137                  'organization_name': organization_name,
138                  'name': creator_name}
139        else:
140            args = {}
141
142    elif state == 'enable_reply_user_notification':
143        template = 'reply_notify_template'
144        subject = 'Someone replied to your comment on "%s"' % getParent(context).Title()
145        di_parrent = getDIParent(reply)
146        if di_parrent:
147            user_email = getEmail(di_parrent, context)
148            if user_email:
149                args={'mto': user_email,
150                      'mfrom': admin_email,
151                      'obj': reply_parent,
152                      'organization_name': organization_name,
153                      'name': di_parrent.getOwnerTuple()[1]}
154            else:
155                args = {}
156        else:
157            args = {}
158
159    elif state == 'enable_published_notification':
160        template = 'published_comment_template'
161        user_email = getParentOwnerEmail(reply, context)
162        if user_email:
163            args={'mto':user_email,
164                  'mfrom':admin_email,
165                  'obj':reply_parent,
166                  'organization_name':organization_name}
167            subject = '[%s] New comment added' % organization_name
168        else:
169            args = {}
170
171    elif state == 'enable_approve_notification':
172        template = 'approve_comment_template'
173        user_email = getProp(context, "email_discussion_manager", None)
174        if user_email:
175            args={'mto':user_email,
176                  'mfrom':admin_email,
177                  'obj':reply_parent,
178                  'organization_name':organization_name}
179            subject = '[%s] New comment awaits moderation' % organization_name
180        else:
181            args = {}
182
183    elif state in ('enable_authenticated_report_abuse', 'enable_anonymous_report_abuse'):
184        template = 'report_abuse_template'
185        user_email = getProp(context, "email_discussion_manager", None)
186        if user_email:
187            message = context.REQUEST.get('message')
188            comment_id = context.REQUEST.get('comment_id')
189            pd = context.portal_discussion
190            dl = pd.getDiscussionFor(context)
191            comment = dl._container.get(comment_id)
192            args = {'mto': user_email,
193                    'mfrom': admin_email,
194                    'obj': reply_parent,
195                    'message':message,
196                    'organization_name': organization_name,
197                    'name': creator_name,
198                    'comment_id':comment_id,
199                    'comment_desc':comment.description,
200                    'comment_text':comment.text
201                    }
202            subject = '[%s] A comment on "%s" has been reported for abuse.' \
203                            % (organization_name, getParent(context).Title())
204        else:
205            args = {}
206
207    if args:
208        msg = getMsg(context, template, args)
209        p_utils = context.plone_utils
210        site_props = context.portal_properties.site_properties
211        host = p_utils.getMailHost()
212        try:
213            host.secureSend(msg, user_email, admin_email,
214                            subject = subject,
215                            subtype = 'plain',
216                            debug = False,
217                            charset = site_props.getProperty('default_charset', 'utf-8'),
218                            From = admin_email)
219        except smtplib.SMTPRecipientsRefused:
220            log.error(_('SMTPRecipientsRefused: Could not send the email'
221            'notification. Have you configured an email server for Plone?'))
222           
223
224
225def setStatusMsg(state, context, msg):
226    context.plone_utils.addPortalMessage(msg)
227
Note: See TracBrowser for help on using the repository browser.