source: products/quintagroup.plonecomments/branches/jquery/quintagroup/plonecomments/utils.py @ 2137

Last change on this file since 2137 was 2137, checked in by kroman0, 14 years ago

PEP8 fixes

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