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

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

Fixed issue #7

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