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

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

changes for pep8

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":
139                safe_unicode(getParent(context).title_or_id())}),
140            context=context.REQUEST)
141        if user_email:
142            template = 'notify_comment_template'
143            args = {'mto': user_email,
144                    'mfrom': admin_email,
145                    'obj': reply_parent,
146                    'organization_name': organization_name,
147                    'name': creator_name}
148        else:
149            args = {}
150
151    elif state == 'enable_rejected_user_notification':
152        subject = translate(_(u"rejected_user_notification_subject",
153            default=u"Your comment on ${title} was not approved",
154            mapping={u"title":
155                safe_unicode(getParent(context).title_or_id())}),
156            context=context.REQUEST)
157        if user_email:
158            template = 'rejected_comment_template'
159            args = {'mto': user_email,
160                    'mfrom': admin_email,
161                    'obj': reply_parent,
162                    'organization_name': organization_name,
163                    'name': creator_name}
164        else:
165            args = {}
166
167    elif state == 'enable_reply_user_notification':
168        template = 'reply_notify_template'
169        subject = translate(_(u"reply_user_notification_subject",
170            default=u"Someone replied to your comment on ${title}",
171            mapping={u"title":
172                safe_unicode(getParent(context).title_or_id())}),
173            context=context.REQUEST)
174        di_parrent = getDIParent(reply)
175        if di_parrent:
176            user_email = getEmail(di_parrent, context)
177            if user_email:
178                args = {'mto': user_email,
179                        'mfrom': admin_email,
180                        'obj': reply_parent,
181                        'organization_name': organization_name,
182                        'name': di_parrent.getOwnerTuple()[1]}
183            else:
184                args = {}
185        else:
186            args = {}
187
188    elif state == 'enable_published_notification':
189        template = 'published_comment_template'
190        user_email = getParentOwnerEmail(reply, context)
191        if user_email:
192            args = {'mto': user_email,
193                    'mfrom': admin_email,
194                    'obj': reply_parent,
195                    'organization_name': organization_name}
196            subject = translate(_(u"published_notification_subject",
197                default=u"[${organization_name}] New comment added",
198                mapping={u"organization_name": organization_name}),
199                context=context.REQUEST)
200        else:
201            args = {}
202
203    elif state == 'enable_approve_notification':
204        template = 'approve_comment_template'
205        user_email = getProp(context, "email_discussion_manager", None)
206        if user_email:
207            args = {'mto': user_email,
208                    'mfrom': admin_email,
209                    'obj': reply_parent,
210                    'organization_name': organization_name}
211            subject = translate(_(u"approve_notification_subject",
212                default=u"[${organization_name}] New comment awaits "
213                        u"moderation",
214                mapping={u"organization_name": organization_name}),
215                context=context.REQUEST)
216        else:
217            args = {}
218
219    elif state in ('enable_authenticated_report_abuse',
220                   'enable_anonymous_report_abuse'):
221        template = 'report_abuse_template'
222        user_email = getProp(context, "email_discussion_manager", None)
223        if user_email:
224            message = context.REQUEST.get('message')
225            comment_id = context.REQUEST.get('comment_id')
226            pd = context.portal_discussion
227            dl = pd.getDiscussionFor(context)
228            comment = dl._container.get(comment_id)
229            args = {'mto': user_email,
230                    'mfrom': admin_email,
231                    'obj': reply_parent,
232                    'message': message,
233                    'organization_name': organization_name,
234                    'name': creator_name,
235                    'comment_id': comment_id,
236                    'comment_desc': comment.description,
237                    'comment_text': comment.text}
238            subject = translate(_(u"report_abuse_subject",
239                default=u"[${organization_name}] A comment on ${title} has "
240                        u"been reported for abuse.",
241                mapping={u"organization_name": organization_name,
242                         u"title":
243                             safe_unicode(getParent(context).title_or_id())}),
244                context=context.REQUEST)
245        else:
246            args = {}
247
248    if args:
249        msg = getMsg(context, template, args)
250        site_properties = context.portal_properties.site_properties
251        charset = site_properties.getProperty('default_charset', 'utf-8')
252        msg = msg.encode(charset)
253        host = context.plone_utils.getMailHost()
254        try:
255            host.secureSend(msg, user_email, admin_email, subject=subject,
256                            subtype='plain', debug=False, charset=charset)
257        except (smtplib.SMTPRecipientsRefused, smtplib.SMTPServerDisconnected):
258            setStatusMsg(None, context,
259                _('Could not send the email notification. Have you configured '
260                  'an email server for Plone?'))
Note: See TracBrowser for help on using the repository browser.