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

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

Pyflakes and pep8 fixes #3

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