source: products/quintagroup.plonecomments/trunk/quintagroup/plonecomments/utils.py @ 3119

Last change on this file since 3119 was 3119, checked in by kroman0, 13 years ago

Pyflakes and pep8 fixes #6

File size: 10.2 KB
Line 
1import smtplib
2from zope.i18nmessageid import MessageFactory
3_ = MessageFactory("quintagroup.plonecomments")
4from Products.CMFCore.utils import getToolByName
5from Products.CMFPlone.utils import safe_unicode
6
7
8# Get apropriate property from (propery_sheeet) configlet
9def getProp(self, prop_name, marker=None):
10    result = marker
11    pp = getToolByName(self, 'portal_properties')
12    config_ps = getattr(pp, 'qPloneComments', None)
13    if config_ps:
14        result = getattr(config_ps, prop_name, marker)
15    return result
16
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
25
26def setAnonymCommenting(context, allow=False):
27    portal = getToolByName(context, 'portal_url').getPortalObject()
28    roles = [r['name']
29             for r in portal.rolesOfPermission('Reply to item')
30             if r['selected']]
31    if allow:
32        if not 'Anonymous' in roles:
33            roles.append('Anonymous')
34            portal.manage_permission('Reply to item', roles, 1)
35    else:
36        if 'Anonymous' in roles:
37            roles.remove('Anonymous')
38            portal.manage_permission('Reply to item', roles, 1)
39
40
41def manage_mails(reply, context, action):
42    def sendMails(props, actions, key):
43        for p in props:
44            if p in actions[key]:
45                send_email(reply, context, p)
46
47    prop_sheet = context.portal_properties['qPloneComments']
48    props = filter(lambda x: prop_sheet.getProperty(x), \
49                   prop_sheet.propertyIds())
50
51    actions = {
52        'onPublish':                    ('enable_approve_user_notification',
53                                         'enable_reply_user_notification',
54                                         'enable_published_notification',),
55        'onDelete':                     ('enable_rejected_user_notification',),
56        'onApprove':                    ('enable_approve_notification',),
57        'onAnonymousReportAbuse':       ('enable_anonymous_report_abuse',),
58        'onAuthenticatedReportAbuse':   ('enable_authenticated_report_abuse',),
59        }
60
61    if action == 'publishing':
62        sendMails(props, actions, 'onPublish')
63
64    elif action == 'deleting':
65        sendMails(props, actions, 'onDelete')
66
67    elif action == 'aproving':
68        sendMails(props, actions, 'onApprove')
69
70    elif action == 'report_abuse':
71        pm = getToolByName(context, 'portal_membership')
72        if pm.isAnonymousUser():
73            sendMails(props, actions, 'onAnonymousReportAbuse')
74        else:
75            sendMails(props, actions, 'onAuthenticatedReportAbuse')
76
77
78def getMsg(context, template, args):
79    return getattr(context, template)(**args)
80
81
82def allowEmail(context, reply, state, creator):
83    condition = getattr(context, 'emailCommentNotification', True)
84    if callable(condition):
85        condition = condition(reply=reply, state=state, creator=creator)
86    return condition
87
88
89def send_email(reply, context, state):
90    def getEmail(obj, context):
91        email = obj.getProperty('email', None)
92        if email is None:
93            creators = hasattr(obj, 'listCreators') and obj.listCreators() or \
94                [obj.Creator(), ]
95            userid = creators and creators[0] or ""
96            portal_membership = getToolByName(context, 'portal_membership')
97            creator = portal_membership.getMemberById(userid)
98            if creator and allowEmail(context, reply, state, creator):
99                return creator.getProperty('email', '')
100        else:
101            return email
102        return ''
103
104    def getParent(reply):
105        if reply.meta_type == 'Discussion Item':
106            reply = reply.inReplyTo()
107            return getParent(reply)
108        return reply
109
110    def getDIParent(reply):
111        r = reply.inReplyTo()
112        return r.meta_type == 'Discussion Item' and r or None
113
114    def getParentOwnerEmail(reply, context):
115        creator_id = getParent(reply).getOwnerTuple()[1]
116        portal_membership = getToolByName(context, 'portal_membership')
117        creator = portal_membership.getMemberById(creator_id)
118        if creator and allowEmail(context, reply, state, creator):
119            return creator.getProperty('email', '')
120        return ''
121
122    args = {}
123    if reply:
124        user_email = getEmail(reply, context)
125        reply_parent = getParent(reply)
126
127    organization_name = getProp(context, 'email_subject_prefix', '')
128    creator_name = reply.getOwnerTuple()[1]
129    portal = getToolByName(context, 'portal_url').getPortalObject()
130    admin_email = portal.getProperty('email_from_address')
131    translate = getToolByName(context, 'translation_service').translate
132    subject = ''
133    if state == 'enable_approve_user_notification':
134        subject = translate(_(u"approve_user_notification_subject",
135            default=u"Your comment on ${title} is now published",
136            mapping={u"title":
137                safe_unicode(getParent(context).title_or_id())}),
138            context=context.REQUEST)
139        if user_email:
140            template = 'notify_comment_template'
141            args = {'mto': user_email,
142                    'mfrom': admin_email,
143                    'obj': reply_parent,
144                    'organization_name': organization_name,
145                    'name': creator_name}
146        else:
147            args = {}
148
149    elif state == 'enable_rejected_user_notification':
150        subject = translate(_(u"rejected_user_notification_subject",
151            default=u"Your comment on ${title} was not approved",
152            mapping={u"title":
153                safe_unicode(getParent(context).title_or_id())}),
154            context=context.REQUEST)
155        if user_email:
156            template = 'rejected_comment_template'
157            args = {'mto': user_email,
158                    'mfrom': admin_email,
159                    'obj': reply_parent,
160                    'organization_name': organization_name,
161                    'name': creator_name}
162        else:
163            args = {}
164
165    elif state == 'enable_reply_user_notification':
166        template = 'reply_notify_template'
167        subject = translate(_(u"reply_user_notification_subject",
168            default=u"Someone replied to your comment on ${title}",
169            mapping={u"title":
170                safe_unicode(getParent(context).title_or_id())}),
171            context=context.REQUEST)
172        di_parrent = getDIParent(reply)
173        if di_parrent:
174            user_email = getEmail(di_parrent, context)
175            if user_email:
176                args = {'mto': user_email,
177                        'mfrom': admin_email,
178                        'obj': reply_parent,
179                        'organization_name': organization_name,
180                        'name': di_parrent.getOwnerTuple()[1]}
181            else:
182                args = {}
183        else:
184            args = {}
185
186    elif state == 'enable_published_notification':
187        template = 'published_comment_template'
188        user_email = getParentOwnerEmail(reply, context)
189        if user_email:
190            args = {'mto': user_email,
191                    'mfrom': admin_email,
192                    'obj': reply_parent,
193                    'organization_name': organization_name}
194            subject = translate(_(u"published_notification_subject",
195                default=u"[${organization_name}] New comment added",
196                mapping={u"organization_name": organization_name}),
197                context=context.REQUEST)
198        else:
199            args = {}
200
201    elif state == 'enable_approve_notification':
202        template = 'approve_comment_template'
203        user_email = getProp(context, "email_discussion_manager", None)
204        if user_email:
205            args = {'mto': user_email,
206                    'mfrom': admin_email,
207                    'obj': reply_parent,
208                    'organization_name': organization_name}
209            subject = translate(_(u"approve_notification_subject",
210                default=u"[${organization_name}] New comment awaits "
211                        u"moderation",
212                mapping={u"organization_name": organization_name}),
213                context=context.REQUEST)
214        else:
215            args = {}
216
217    elif state in ('enable_authenticated_report_abuse',
218                   'enable_anonymous_report_abuse'):
219        template = 'report_abuse_template'
220        user_email = getProp(context, "email_discussion_manager", None)
221        if user_email:
222            message = context.REQUEST.get('message')
223            comment_id = context.REQUEST.get('comment_id')
224            pd = context.portal_discussion
225            dl = pd.getDiscussionFor(context)
226            comment = dl._container.get(comment_id)
227            args = {'mto': user_email,
228                    'mfrom': admin_email,
229                    'obj': reply_parent,
230                    'message': message,
231                    'organization_name': organization_name,
232                    'name': creator_name,
233                    'comment_id': comment_id,
234                    'comment_desc': comment.description,
235                    'comment_text': comment.text}
236            subject = translate(_(u"report_abuse_subject",
237                default=u"[${organization_name}] A comment on ${title} has "
238                        u"been reported for abuse.",
239                mapping={u"organization_name": organization_name,
240                         u"title":
241                             safe_unicode(getParent(context).title_or_id())}),
242                context=context.REQUEST)
243        else:
244            args = {}
245
246    if args:
247        msg = getMsg(context, template, args)
248        site_properties = context.portal_properties.site_properties
249        charset = site_properties.getProperty('default_charset', 'utf-8')
250        msg = msg.encode(charset)
251        host = context.plone_utils.getMailHost()
252        try:
253            host.secureSend(msg, user_email, admin_email, subject=subject,
254                            subtype='plain', debug=False, charset=charset)
255        except (smtplib.SMTPRecipientsRefused, smtplib.SMTPServerDisconnected):
256            setStatusMsg(None, context,
257                _('Could not send the email notification. '
258                  'Have you configured an email server for Plone?'))
259
260
261def setStatusMsg(state, context, msg):
262    context.plone_utils.addPortalMessage(msg)
Note: See TracBrowser for help on using the repository browser.