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

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

Pyflakes and pep8 fixes

File size: 9.7 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 = { 'onPublish': ('enable_approve_user_notification',
47                              'enable_reply_user_notification',
48                              'enable_published_notification',),
49                'onDelete' : ('enable_rejected_user_notification',),
50                'onApprove': ('enable_approve_notification',),
51                'onAnonymousReportAbuse': ('enable_anonymous_report_abuse',),
52                'onAuthenticatedReportAbuse': ('enable_authenticated_report_abuse',),}
53
54    if action == 'publishing':
55        sendMails(props, actions, 'onPublish')
56
57    elif action == 'deleting':
58        sendMails(props, actions, 'onDelete')
59
60    elif action == 'aproving':
61        sendMails(props, actions, 'onApprove')
62
63    elif action == 'report_abuse':
64        pm = getToolByName(context, 'portal_membership')
65        if pm.isAnonymousUser():
66            sendMails(props, actions, 'onAnonymousReportAbuse')
67        else:
68            sendMails(props, actions, 'onAuthenticatedReportAbuse')
69
70def getMsg(context, template, args):
71    return getattr(context, template)(**args)
72
73def allowEmail(context, reply, state, creator):
74    condition = getattr(context, 'emailCommentNotification', True)
75    if callable(condition):
76        condition = condition(reply=reply, state=state, creator=creator)
77    return condition
78
79def send_email(reply, context, state):
80    def getEmail(obj, context):
81        email = obj.getProperty('email', None)
82        if email is None:
83            creators = hasattr(obj, 'listCreators') and obj.listCreators() or [obj.Creator(),]
84            userid = creators and creators[0] or ""
85            creator = getToolByName(context, 'portal_membership').getMemberById(userid)
86            if creator and allowEmail(context, reply, state, creator):
87                return creator.getProperty('email', '')
88        else:
89            return email
90        return ''
91
92    def getParent(reply):
93        if reply.meta_type == 'Discussion Item':
94            reply = reply.inReplyTo()
95            return getParent(reply)
96        return reply
97
98    def getDIParent(reply):
99        r = reply.inReplyTo()
100        return r.meta_type == 'Discussion Item' and r or None
101
102    def getParentOwnerEmail(reply, context):
103        creator_id = getParent(reply).getOwnerTuple()[1]
104        creator = getToolByName(context, 'portal_membership').getMemberById(creator_id)
105        if creator and allowEmail(context, reply, state, creator):
106            return creator.getProperty('email', '')
107        return ''
108
109    args = {}
110    if reply:
111        user_email = getEmail(reply, context)
112        reply_parent = getParent(reply)
113
114    organization_name = getProp(context, 'email_subject_prefix', '')
115    creator_name = reply.getOwnerTuple()[1]
116    admin_email = context.portal_url.getPortalObject().getProperty('email_from_address')
117    translate = getToolByName(context, 'translation_service').translate
118    subject = ''
119    if state == 'enable_approve_user_notification':
120        subject = translate(_(u"approve_user_notification_subject",
121            default=u"Your comment on ${title} is now published",
122            mapping={u"title": safe_unicode(getParent(context).title_or_id())}),
123            context=context.REQUEST)
124        if user_email:
125            template = 'notify_comment_template'
126            args={'mto': user_email,
127                  'mfrom': admin_email,
128                  'obj': reply_parent,
129                  'organization_name': organization_name,
130                  'name': creator_name}
131        else:
132            args = {}
133
134    elif state == 'enable_rejected_user_notification':
135        subject = translate(_(u"rejected_user_notification_subject",
136            default=u"Your comment on ${title} was not approved",
137            mapping={u"title": safe_unicode(getParent(context).title_or_id())}),
138            context=context.REQUEST)
139        if user_email:
140            template = 'rejected_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_reply_user_notification':
150        template = 'reply_notify_template'
151        subject = translate(_(u"reply_user_notification_subject",
152            default=u"Someone replied to your comment on ${title}",
153            mapping={u"title": safe_unicode(getParent(context).title_or_id())}),
154            context=context.REQUEST)
155        di_parrent = getDIParent(reply)
156        if di_parrent:
157            user_email = getEmail(di_parrent, context)
158            if user_email:
159                args={'mto': user_email,
160                      'mfrom': admin_email,
161                      'obj': reply_parent,
162                      'organization_name': organization_name,
163                      'name': di_parrent.getOwnerTuple()[1]}
164            else:
165                args = {}
166        else:
167            args = {}
168
169    elif state == 'enable_published_notification':
170        template = 'published_comment_template'
171        user_email = getParentOwnerEmail(reply, context)
172        if user_email:
173            args={'mto':user_email,
174                  'mfrom':admin_email,
175                  'obj':reply_parent,
176                  'organization_name':organization_name}
177            subject = translate(_(u"published_notification_subject",
178                default=u"[${organization_name}] New comment added",
179                mapping={u"organization_name": organization_name}),
180                context=context.REQUEST)
181        else:
182            args = {}
183
184    elif state == 'enable_approve_notification':
185        template = 'approve_comment_template'
186        user_email = getProp(context, "email_discussion_manager", None)
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"approve_notification_subject",
193                default=u"[${organization_name}] New comment awaits moderation",
194                mapping={u"organization_name": organization_name}),
195                context=context.REQUEST)
196        else:
197            args = {}
198
199    elif state in ('enable_authenticated_report_abuse', 'enable_anonymous_report_abuse'):
200        template = 'report_abuse_template'
201        user_email = getProp(context, "email_discussion_manager", None)
202        if user_email:
203            message = context.REQUEST.get('message')
204            comment_id = context.REQUEST.get('comment_id')
205            pd = context.portal_discussion
206            dl = pd.getDiscussionFor(context)
207            comment = dl._container.get(comment_id)
208            args = {'mto': user_email,
209                    'mfrom': admin_email,
210                    'obj': reply_parent,
211                    'message': message,
212                    'organization_name': organization_name,
213                    'name': creator_name,
214                    'comment_id': comment_id,
215                    'comment_desc': comment.description,
216                    'comment_text': comment.text}
217            subject = translate(_(u"report_abuse_subject",
218                default=u"[${organization_name}] A comment on ${title} has "
219                        u"been reported for abuse.",
220                mapping={u"organization_name": organization_name,
221                         u"title":
222                             safe_unicode(getParent(context).title_or_id())}),
223                context=context.REQUEST)
224        else:
225            args = {}
226
227    if args:
228        msg = getMsg(context, template, args)
229        charset = context.portal_properties.site_properties.getProperty('default_charset', 'utf-8')
230        msg = msg.encode(charset)
231        host = context.plone_utils.getMailHost()
232        try:
233            host.secureSend(msg, user_email, admin_email, subject=subject,
234                            subtype='plain', debug=False, charset=charset)
235        except (smtplib.SMTPRecipientsRefused,smtplib.SMTPServerDisconnected):
236            setStatusMsg(None, context,
237                _('Could not send the email notification. Have you configured an email server for Plone?'))
238
239def setStatusMsg(state, context, msg):
240    context.plone_utils.addPortalMessage(msg)
Note: See TracBrowser for help on using the repository browser.