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

Last change on this file since 1222 was 1201, checked in by liebster, 15 years ago

Added "report abuse" feature contributed by jcbrand.

File size: 8.4 KB
Line 
1import smtplib
2from Products.CMFPlone import MessageFactory
3from Products.CMFCore.utils import getToolByName
4from Products.CMFPlone import PloneMessageFactory as _
5from config import warning
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    if allow:
26        portal.manage_permission('Reply to item', ['Anonymous','Manager','Member'], 1)
27    else:
28        portal.manage_permission('Reply to item', ['Manager','Member'], 1)
29
30def manage_mails(reply, context, action):
31    def sendMails(props, actions, key):
32        for p in props:
33            if p in actions[key]:
34                send_email(reply, context, p)
35
36    prop_sheet = context.portal_properties['qPloneComments']
37    props = filter(lambda x: prop_sheet.getProperty(x), prop_sheet.propertyIds())
38
39    actions = { 'onPublish': ('enable_approve_user_notification',
40                              'enable_reply_user_notification',
41                              'enable_published_notification'),
42                'onDelete' :  ('enable_rejected_user_notification',),
43                'onApprove': ('enable_approve_notification',),
44                'onAnonymousReportAbuse': ('enable_anonymous_report_abuse',),
45                'onAuthenticatedReportAbuse': ('enable_authenticated_report_abuse')}
46
47    if action == 'publishing':
48        sendMails(props, actions, 'onPublish')
49
50    elif action == 'deleting':
51        sendMails(props, actions, 'onDelete')
52
53    elif action == 'aproving':
54        sendMails(props, actions, 'onApprove')
55
56    elif action == 'report_abuse':
57        pm = getToolByName(context, 'portal_membership')
58        if pm.isAnonymousUser():
59            sendMails(props, actions, 'onAnonymousReportAbuse')
60        else:
61            sendMails(props, actions, 'onAuthenticatedReportAbuse')
62
63def getMsg(context, template, args):
64    return getattr(context, template)(**args)
65
66def allowEmail(context, reply, state, creator):
67    condition = getattr(context, 'emailCommentNotification', True)
68    if callable(condition):
69        condition = condition(reply=reply, state=state, creator=creator)
70    return condition
71
72def send_email(reply, context, state):
73    def getEmail(obj, context):
74        email = obj.getProperty('email', None)
75        if email is None:
76            creators = hasattr(obj, 'listCreators') and obj.listCreators() or [obj.Creator(),]
77            userid = creators and creators[0] or ""
78            creator = getToolByName(context, 'portal_membership').getMemberById(userid)
79            if creator and allowEmail(context, reply, state, creator):
80                return creator.getProperty('email', '')
81        else:
82            return email
83        return ''
84
85    def getParent(reply):
86        if reply.meta_type == 'Discussion Item':
87            reply = reply.inReplyTo()
88            return getParent(reply)
89        return reply
90
91    def getDIParent(reply):
92        r = reply.inReplyTo()
93        return r.meta_type == 'Discussion Item' and r or None
94
95    def getParentOwnerEmail(reply, context):
96        creator_id = getParent(reply).getOwnerTuple()[1]
97        creator = getToolByName(context, 'portal_membership').getMemberById(creator_id)
98        if creator and allowEmail(context, reply, state, creator):
99            return creator.getProperty('email', '')
100        return ''
101
102    args = {}
103    if reply:
104        user_email = getEmail(reply, context)
105        reply_parent = getParent(reply)
106
107    organization_name = getProp(context, 'email_subject_prefix', '')
108    creator_name = reply.getOwnerTuple()[1]
109    admin_email = context.portal_url.getPortalObject().getProperty('email_from_address')
110
111    subject = ''
112    if state == 'enable_approve_user_notification':
113        subject = 'Your comment on %s is now published' % getParent(context).Title()
114        if user_email:
115            template = 'notify_comment_template'
116            args={'mto': user_email,
117                  'mfrom': admin_email,
118                  'obj': reply_parent,
119                  'organization_name': organization_name,
120                  'name': creator_name}
121        else:
122            args = {}
123
124    elif state == 'enable_rejected_user_notification':
125        subject = 'Your comment on %s was not approved' % getParent(context).Title()
126        if user_email:
127            template = 'rejected_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_reply_user_notification':
137        template = 'reply_notify_template'
138        subject = 'Someone replied to your comment on %s' % getParent(context).Title()
139        di_parrent = getDIParent(reply)
140        if di_parrent:
141            user_email = getEmail(di_parrent, context)
142            if user_email:
143                args={'mto': user_email,
144                      'mfrom': admin_email,
145                      'obj': reply_parent,
146                      'organization_name': organization_name,
147                      'name': di_parrent.getOwnerTuple()[1]}
148            else:
149                args = {}
150        else:
151            args = {}
152
153    elif state == 'enable_published_notification':
154        template = 'published_comment_template'
155        user_email = getParentOwnerEmail(reply, context)
156        if user_email:
157            args={'mto':user_email,
158                  'mfrom':admin_email,
159                  'obj':reply_parent,
160                  'organization_name':organization_name}
161            subject = '[%s] New comment added' % organization_name
162        else:
163            args = {}
164
165    elif state == 'enable_approve_notification':
166        template = 'approve_comment_template'
167        user_email = getProp(context, "email_discussion_manager", None)
168        if user_email:
169            args={'mto':user_email,
170                  'mfrom':admin_email,
171                  'obj':reply_parent,
172                  'organization_name':organization_name}
173            subject = '[%s] New comment awaits moderation' % organization_name
174        else:
175            args = {}
176
177    elif state in ('enable_authenticated_report_abuse', 'enable_anonymous_report_abuse'):
178        template = 'report_abuse_template'
179        user_email = getProp(context, "email_discussion_manager", None)
180        if user_email:
181            message = context.REQUEST.get('message')
182            comment_id = context.REQUEST.get('comment_id')
183            pd = context.portal_discussion
184            dl = pd.getDiscussionFor(context)
185            comment = dl._container.get(comment_id)
186            args = {'mto': user_email,
187                    'mfrom': admin_email,
188                    'obj': reply_parent,
189                    'message':message,
190                    'organization_name': organization_name,
191                    'name': creator_name,
192                    'comment_id':comment_id,
193                    'comment_desc':comment.description,
194                    'comment_text':comment.text
195                    }
196            subject = '[%s] A comment on "%s" has been reported for abuse.' \
197                            % (organization_name, getParent(context).Title())
198        else:
199            args = {}
200
201    if args:
202        msg = getMsg(context, template, args)
203        p_utils = context.plone_utils
204        site_props = context.portal_properties.site_properties
205        host = p_utils.getMailHost()
206        try:
207            host.secureSend(msg, user_email, admin_email,
208                            subject = subject,
209                            subtype = 'plain',
210                            debug = False,
211                            charset = site_props.getProperty('default_charset', 'utf-8'),
212                            From = admin_email)
213        except smtplib.SMTPRecipientsRefused:
214            log.error(_('SMTPRecipientsRefused: Could not send the email'
215            'notification. Have you configured an email server for Plone?'))
216
217def setStatusMsg(state, context, msg):
218    context.plone_utils.addPortalMessage(msg)
Note: See TracBrowser for help on using the repository browser.