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

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

Pyflakes and pep8 fixes #4

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