-
-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathcomment.py
More file actions
491 lines (410 loc) · 15.2 KB
/
Copy pathcomment.py
File metadata and controls
491 lines (410 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
"""The default comment class and factory."""
from AccessControl import ClassSecurityInfo
from AccessControl.SecurityManagement import getSecurityManager
from Acquisition import aq_base
from Acquisition import aq_parent
from Acquisition import Implicit
from datetime import timezone
from OFS.owner import Owned
from OFS.role import RoleManager
from OFS.Traversable import Traversable
from persistent import Persistent
from plone.app.discussion import _
from plone.app.discussion.events import CommentAddedEvent
from plone.app.discussion.events import CommentModifiedEvent
from plone.app.discussion.events import CommentRemovedEvent
from plone.app.discussion.events import ReplyAddedEvent
from plone.app.discussion.events import ReplyModifiedEvent
from plone.app.discussion.events import ReplyRemovedEvent
from plone.app.discussion.interfaces import IComment
from plone.app.discussion.interfaces import IConversation
from plone.app.discussion.interfaces import IDiscussionSettings
from plone.app.event.base import localized_now
from plone.base.interfaces.controlpanel import IMailSchema
from plone.base.utils import safe_text
from plone.registry.interfaces import IRegistry
from Products.CMFCore import permissions
from Products.CMFCore.CMFCatalogAware import CatalogAware
from Products.CMFCore.CMFCatalogAware import WorkflowAware
from Products.CMFCore.DynamicType import DynamicType
from Products.CMFCore.utils import getToolByName
from smtplib import SMTPException
from zope.annotation.interfaces import IAnnotatable
from zope.component import getUtility
from zope.component import queryUtility
from zope.component.factory import Factory
from zope.event import notify
from zope.globalrequest import getRequest
from zope.i18n import translate
from zope.i18nmessageid import Message
from zope.interface import implementer
import logging
COMMENT_TITLE = _(
"comment_title",
default="${author_name} on ${content}",
)
MAIL_NOTIFICATION_MESSAGE = _(
"mail_notification_message",
default='A comment on "${title}" '
"has been posted here: ${link}\n\n"
"---\n"
"${text}\n"
"---\n",
)
MAIL_NOTIFICATION_MESSAGE_MODERATOR = _(
"mail_notification_message_moderator2",
default='A comment on "${title}" '
"has been posted by ${commentator}\n"
"here: ${link}\n\n"
"---\n\n"
"${text}\n\n"
"---\n\n"
"Log in to moderate.\n\n",
)
logger = logging.getLogger("plone.app.discussion")
@implementer(IComment)
class Comment(
CatalogAware,
WorkflowAware,
DynamicType,
Traversable,
RoleManager,
Owned,
Implicit,
Persistent,
):
"""A comment.
This object attempts to be as lightweight as possible. We implement a
number of standard methods instead of subclassing, to have total control
over what goes into the object.
"""
security = ClassSecurityInfo()
meta_type = portal_type = "Discussion Item"
# This needs to be kept in sync with types/Discussion_Item.xml title
fti_title = "Comment"
__parent__ = None
comment_id = None # long
in_reply_to = None # long
title = ""
mime_type = None
text = ""
creator = None
creation_date = None
modification_date = None
author_username = None
author_name = None
author_email = None
user_notification = None
# Note: we want to use zope.component.createObject() to instantiate
# comments as far as possible. comment_id and __parent__ are set via
# IConversation.addComment().
def __init__(self):
self.creation_date = self.modification_date = localized_now()
self.mime_type = "text/plain"
user = getSecurityManager().getUser()
if user and user.getId():
aclpath = [x for x in user.getPhysicalPath() if x]
self._owner = (
aclpath,
user.getId(),
)
self.__ac_local_roles__ = {
user.getId(): ["Owner"],
}
def __getattribute__(self, attr):
# In older versions of the add-on dates were set timezone naive.
# In tz aware versions, the value is stored as self._creation_date
if attr in ["creation_date", "modification_date"]:
old_date = super().__getattribute__(attr)
if old_date.tzinfo is None:
# Naive dates were always stored utc
return old_date.replace(tzinfo=timezone.utc)
return old_date
return super().__getattribute__(attr)
@property
def __name__(self):
return self.comment_id and str(self.comment_id) or None
@property
def id(self):
return self.comment_id and str(self.comment_id) or None
def getId(self):
# The id of the comment, as a string.
return self.id
def getText(self, targetMimetype=None):
"""The body text of a comment."""
transforms = getToolByName(self, "portal_transforms")
if targetMimetype is None:
targetMimetype = "text/x-html-safe"
sourceMimetype = getattr(self, "mime_type", None)
if sourceMimetype is None:
registry = queryUtility(IRegistry)
settings = registry.forInterface(IDiscussionSettings, check=False)
sourceMimetype = settings.text_transform
text = self.text
if text is None:
return ""
transform = transforms.convertTo(
targetMimetype, text, context=self, mimetype=sourceMimetype
)
if transform:
return transform.getData()
else:
logger = logging.getLogger("plone.app.discussion")
msg = (
'Transform "{0}" => "{1}" not available. Failed to '
'transform comment "{2}".'
)
logger.error(
msg.format(
sourceMimetype,
targetMimetype,
self.absolute_url(),
),
)
return text
def Title(self):
# The title of the comment.
if self.title:
return self.title
if not self.author_name:
author_name = translate(
Message(
_(
"label_anonymous",
default="Anonymous",
),
),
context=getRequest(),
)
else:
author_name = self.author_name
# Fetch the content object (the parent of the comment is the
# conversation, the parent of the conversation is the content object).
content = aq_base(self.__parent__.__parent__)
title = translate(
Message(
COMMENT_TITLE,
mapping={
"author_name": safe_text(author_name),
"content": safe_text(content.Title()),
},
),
context=getRequest(),
)
return title
def Creator(self):
# The name of the person who wrote the comment.
return self.creator or self.author_name
@security.protected(permissions.View)
def Type(self):
# The Discussion Item content type.
return self.fti_title
# CMF's event handlers assume any IDynamicType has these :(
def opaqueItems(self): # pragma: no cover
return []
def opaqueIds(self): # pragma: no cover
return []
def opaqueValues(self): # pragma: no cover
return []
CommentFactory = Factory(Comment)
def notify_workflow(obj, event):
"""Tell the workflow tool when a comment is added"""
tool = getToolByName(obj, "portal_workflow", None)
if tool is not None:
tool.notifyCreated(obj)
def notify_content_object(obj, event):
"""Tell the content object when a comment is added"""
content_obj = aq_parent(aq_parent(obj))
content_obj.reindexObject(
idxs=("total_comments", "last_comment_date", "commentators")
)
def notify_content_object_deleted(obj, event):
"""Remove all comments of a content object when the content object has been
deleted.
"""
if IAnnotatable.providedBy(obj):
conversation = IConversation(obj)
while conversation:
del conversation[list(conversation.keys())[0]]
def notify_comment_added(obj, event):
"""Notify custom discussion events when a comment is added or replied"""
conversation = aq_parent(obj)
context = aq_parent(conversation)
if getattr(obj, "in_reply_to", None):
return notify(ReplyAddedEvent(context, obj))
return notify(CommentAddedEvent(context, obj))
def notify_comment_modified(obj, event):
"""Notify custom discussion events when a comment, or a reply, is modified"""
conversation = aq_parent(obj)
context = aq_parent(conversation)
if getattr(obj, "in_reply_to", None):
return notify(ReplyModifiedEvent(context, obj))
return notify(CommentModifiedEvent(context, obj))
def notify_comment_removed(obj, event):
"""Notify custom discussion events when a comment or reply is removed"""
conversation = aq_parent(obj)
context = aq_parent(conversation)
if getattr(obj, "in_reply_to", None):
return notify(ReplyRemovedEvent(context, obj))
return notify(CommentRemovedEvent(context, obj))
def notify_content_object_moved(obj, event):
"""Update all comments of a content object that has been moved."""
if (
event.oldParent is None
or event.newParent is None
or event.oldName is None
or event.newName is None
):
return
# This method is also called for sublocations of moved objects. We
# therefore can't assume that event.object == obj and event.
# {old,new}{Parent,Name} may refer to the actually moved object further up
# in the object hierarchy. The object is already moved at this point. so
# obj.getPhysicalPath returns the new path get the part of the path that
# was moved.
moved_path = obj.getPhysicalPath()[len(event.newParent.getPhysicalPath()) + 1 :]
# Remove comments at the old location from catalog
catalog = getToolByName(obj, "portal_catalog")
old_path = "/".join(
event.oldParent.getPhysicalPath() + (event.oldName,) + moved_path,
)
brains = catalog.searchResults(
dict(
path={"query": old_path},
portal_type="Discussion Item",
)
)
for brain in brains:
catalog.uncatalog_object(brain.getPath())
# Reindex comment at the new location
conversation = IConversation(obj, None)
if conversation is not None:
for comment in conversation.getComments():
comment.reindexObject()
def notify_user(obj, event):
"""Tell users when a comment has been added.
This method composes and sends emails to all users that have added a
comment to this conversation and enabled user notification.
This requires the user_notification setting to be enabled in the
discussion control panel.
"""
# Check if user notification is enabled
registry = queryUtility(IRegistry)
settings = registry.forInterface(IDiscussionSettings, check=False)
if not settings.user_notification_enabled:
return
# Get information that are necessary to send an email
mail_host = getToolByName(obj, "MailHost")
registry = getUtility(IRegistry)
mail_settings = registry.forInterface(IMailSchema, prefix="plone")
sender = mail_settings.email_from_address
# Check if a sender address is available
if not sender:
return
# Compose and send emails to all users that have add a comment to this
# conversation and enabled user_notification.
conversation = aq_parent(obj)
content_object = aq_parent(conversation)
# Avoid sending multiple notification emails to the same person
# when he has commented multiple times.
emails = set()
for comment in conversation.getComments():
obj_is_not_the_comment = obj != comment
valid_user_email = comment.user_notification and comment.author_email
if obj_is_not_the_comment and valid_user_email:
emails.add(comment.author_email)
if not emails:
return
subject = translate(_("A comment has been posted."), context=getRequest())
message = translate(
Message(
MAIL_NOTIFICATION_MESSAGE,
mapping={
"title": safe_text(content_object.title),
"link": content_object.absolute_url() + "/view#" + obj.id,
"text": obj.text,
},
),
context=getRequest(),
)
for email in emails:
# Send email
try:
mail_host.send(
message,
email,
sender,
subject,
charset="utf-8",
)
except SMTPException:
logger.error(
"SMTP exception while trying to send an " + "email from %s to %s",
sender,
email,
)
def notify_moderator(obj, event):
"""Tell the moderator when a comment needs attention.
This method sends an email to the moderator if comment moderation a new
comment has been added that needs to be approved.
The moderator_notification setting has to be enabled in the discussion
control panel.
Configure the moderator e-mail address in the discussion control panel.
If no moderator is configured but moderator notifications are turned on,
the site admin email (from the mail control panel) will be used.
"""
# Check if moderator notification is enabled
registry = queryUtility(IRegistry)
settings = registry.forInterface(IDiscussionSettings, check=False)
if not settings.moderator_notification_enabled:
return
# Get information that are necessary to send an email
mail_host = getToolByName(obj, "MailHost")
registry = getUtility(IRegistry)
mail_settings = registry.forInterface(IMailSchema, prefix="plone")
sender = mail_settings.email_from_address
if settings.moderator_email:
mto = settings.moderator_email
else:
mto = sender
# Check if a sender address is available
if not sender:
return
conversation = aq_parent(obj)
content_object = aq_parent(conversation)
# Compose email
subject = translate(_("A comment has been posted."), context=getRequest())
message = translate(
Message(
MAIL_NOTIFICATION_MESSAGE_MODERATOR,
mapping={
"title": safe_text(content_object.title),
"link": content_object.absolute_url() + "/view#" + obj.id,
"text": obj.text,
"commentator": obj.author_email
or translate(
Message(
_(
"label_anonymous",
default="Anonymous",
),
),
context=getRequest(),
),
},
),
context=getRequest(),
)
# Send email
try:
mail_host.send(message, mto, sender, subject, charset="utf-8")
except SMTPException as e:
logger.error(
"SMTP exception (%s) while trying to send an "
+ "email notification to the comment moderator "
+ "(from %s to %s, message: %s)",
e,
sender,
mto,
message,
)