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

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

Fixed issue #7

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