PageRenderTime 33ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/comments/moderation.py

https://code.google.com/p/mango-py/
Python | 355 lines | 290 code | 6 blank | 59 comment | 5 complexity | 1f197d835e74c5650f0c663649b92d86 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. """
  2. A generic comment-moderation system which allows configuration of
  3. moderation options on a per-model basis.
  4. To use, do two things:
  5. 1. Create or import a subclass of ``CommentModerator`` defining the
  6. options you want.
  7. 2. Import ``moderator`` from this module and register one or more
  8. models, passing the models and the ``CommentModerator`` options
  9. class you want to use.
  10. Example
  11. -------
  12. First, we define a simple model class which might represent entries in
  13. a Weblog::
  14. from django.db import models
  15. class Entry(models.Model):
  16. title = models.CharField(maxlength=250)
  17. body = models.TextField()
  18. pub_date = models.DateField()
  19. enable_comments = models.BooleanField()
  20. Then we create a ``CommentModerator`` subclass specifying some
  21. moderation options::
  22. from django.contrib.comments.moderation import CommentModerator, moderator
  23. class EntryModerator(CommentModerator):
  24. email_notification = True
  25. enable_field = 'enable_comments'
  26. And finally register it for moderation::
  27. moderator.register(Entry, EntryModerator)
  28. This sample class would apply two moderation steps to each new
  29. comment submitted on an Entry:
  30. * If the entry's ``enable_comments`` field is set to ``False``, the
  31. comment will be rejected (immediately deleted).
  32. * If the comment is successfully posted, an email notification of the
  33. comment will be sent to site staff.
  34. For a full list of built-in moderation options and other
  35. configurability, see the documentation for the ``CommentModerator``
  36. class.
  37. """
  38. import datetime
  39. from django.conf import settings
  40. from django.core.mail import send_mail
  41. from django.contrib.comments import signals
  42. from django.db.models.base import ModelBase
  43. from django.template import Context, loader
  44. from django.contrib import comments
  45. from django.contrib.sites.models import Site
  46. class AlreadyModerated(Exception):
  47. """
  48. Raised when a model which is already registered for moderation is
  49. attempting to be registered again.
  50. """
  51. pass
  52. class NotModerated(Exception):
  53. """
  54. Raised when a model which is not registered for moderation is
  55. attempting to be unregistered.
  56. """
  57. pass
  58. class CommentModerator(object):
  59. """
  60. Encapsulates comment-moderation options for a given model.
  61. This class is not designed to be used directly, since it doesn't
  62. enable any of the available moderation options. Instead, subclass
  63. it and override attributes to enable different options::
  64. ``auto_close_field``
  65. If this is set to the name of a ``DateField`` or
  66. ``DateTimeField`` on the model for which comments are
  67. being moderated, new comments for objects of that model
  68. will be disallowed (immediately deleted) when a certain
  69. number of days have passed after the date specified in
  70. that field. Must be used in conjunction with
  71. ``close_after``, which specifies the number of days past
  72. which comments should be disallowed. Default value is
  73. ``None``.
  74. ``auto_moderate_field``
  75. Like ``auto_close_field``, but instead of outright
  76. deleting new comments when the requisite number of days
  77. have elapsed, it will simply set the ``is_public`` field
  78. of new comments to ``False`` before saving them. Must be
  79. used in conjunction with ``moderate_after``, which
  80. specifies the number of days past which comments should be
  81. moderated. Default value is ``None``.
  82. ``close_after``
  83. If ``auto_close_field`` is used, this must specify the
  84. number of days past the value of the field specified by
  85. ``auto_close_field`` after which new comments for an
  86. object should be disallowed. Default value is ``None``.
  87. ``email_notification``
  88. If ``True``, any new comment on an object of this model
  89. which survives moderation will generate an email to site
  90. staff. Default value is ``False``.
  91. ``enable_field``
  92. If this is set to the name of a ``BooleanField`` on the
  93. model for which comments are being moderated, new comments
  94. on objects of that model will be disallowed (immediately
  95. deleted) whenever the value of that field is ``False`` on
  96. the object the comment would be attached to. Default value
  97. is ``None``.
  98. ``moderate_after``
  99. If ``auto_moderate_field`` is used, this must specify the number
  100. of days past the value of the field specified by
  101. ``auto_moderate_field`` after which new comments for an
  102. object should be marked non-public. Default value is
  103. ``None``.
  104. Most common moderation needs can be covered by changing these
  105. attributes, but further customization can be obtained by
  106. subclassing and overriding the following methods. Each method will
  107. be called with three arguments: ``comment``, which is the comment
  108. being submitted, ``content_object``, which is the object the
  109. comment will be attached to, and ``request``, which is the
  110. ``HttpRequest`` in which the comment is being submitted::
  111. ``allow``
  112. Should return ``True`` if the comment should be allowed to
  113. post on the content object, and ``False`` otherwise (in
  114. which case the comment will be immediately deleted).
  115. ``email``
  116. If email notification of the new comment should be sent to
  117. site staff or moderators, this method is responsible for
  118. sending the email.
  119. ``moderate``
  120. Should return ``True`` if the comment should be moderated
  121. (in which case its ``is_public`` field will be set to
  122. ``False`` before saving), and ``False`` otherwise (in
  123. which case the ``is_public`` field will not be changed).
  124. Subclasses which want to introspect the model for which comments
  125. are being moderated can do so through the attribute ``_model``,
  126. which will be the model class.
  127. """
  128. auto_close_field = None
  129. auto_moderate_field = None
  130. close_after = None
  131. email_notification = False
  132. enable_field = None
  133. moderate_after = None
  134. def __init__(self, model):
  135. self._model = model
  136. def _get_delta(self, now, then):
  137. """
  138. Internal helper which will return a ``datetime.timedelta``
  139. representing the time between ``now`` and ``then``. Assumes
  140. ``now`` is a ``datetime.date`` or ``datetime.datetime`` later
  141. than ``then``.
  142. If ``now`` and ``then`` are not of the same type due to one of
  143. them being a ``datetime.date`` and the other being a
  144. ``datetime.datetime``, both will be coerced to
  145. ``datetime.date`` before calculating the delta.
  146. """
  147. if now.__class__ is not then.__class__:
  148. now = datetime.date(now.year, now.month, now.day)
  149. then = datetime.date(then.year, then.month, then.day)
  150. if now < then:
  151. raise ValueError("Cannot determine moderation rules because date field is set to a value in the future")
  152. return now - then
  153. def allow(self, comment, content_object, request):
  154. """
  155. Determine whether a given comment is allowed to be posted on
  156. a given object.
  157. Return ``True`` if the comment should be allowed, ``False
  158. otherwise.
  159. """
  160. if self.enable_field:
  161. if not getattr(content_object, self.enable_field):
  162. return False
  163. if self.auto_close_field and self.close_after is not None:
  164. close_after_date = getattr(content_object, self.auto_close_field)
  165. if close_after_date is not None and self._get_delta(datetime.datetime.now(), close_after_date).days >= self.close_after:
  166. return False
  167. return True
  168. def moderate(self, comment, content_object, request):
  169. """
  170. Determine whether a given comment on a given object should be
  171. allowed to show up immediately, or should be marked non-public
  172. and await approval.
  173. Return ``True`` if the comment should be moderated (marked
  174. non-public), ``False`` otherwise.
  175. """
  176. if self.auto_moderate_field and self.moderate_after is not None:
  177. moderate_after_date = getattr(content_object, self.auto_moderate_field)
  178. if moderate_after_date is not None and self._get_delta(datetime.datetime.now(), moderate_after_date).days >= self.moderate_after:
  179. return True
  180. return False
  181. def email(self, comment, content_object, request):
  182. """
  183. Send email notification of a new comment to site staff when email
  184. notifications have been requested.
  185. """
  186. if not self.email_notification:
  187. return
  188. recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS]
  189. t = loader.get_template('comments/comment_notification_email.txt')
  190. c = Context({ 'comment': comment,
  191. 'content_object': content_object })
  192. subject = '[%s] New comment posted on "%s"' % (Site.objects.get_current().name,
  193. content_object)
  194. message = t.render(c)
  195. send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
  196. class Moderator(object):
  197. """
  198. Handles moderation of a set of models.
  199. An instance of this class will maintain a list of one or more
  200. models registered for comment moderation, and their associated
  201. moderation classes, and apply moderation to all incoming comments.
  202. To register a model, obtain an instance of ``Moderator`` (this
  203. module exports one as ``moderator``), and call its ``register``
  204. method, passing the model class and a moderation class (which
  205. should be a subclass of ``CommentModerator``). Note that both of
  206. these should be the actual classes, not instances of the classes.
  207. To cease moderation for a model, call the ``unregister`` method,
  208. passing the model class.
  209. For convenience, both ``register`` and ``unregister`` can also
  210. accept a list of model classes in place of a single model; this
  211. allows easier registration of multiple models with the same
  212. ``CommentModerator`` class.
  213. The actual moderation is applied in two phases: one prior to
  214. saving a new comment, and the other immediately after saving. The
  215. pre-save moderation may mark a comment as non-public or mark it to
  216. be removed; the post-save moderation may delete a comment which
  217. was disallowed (there is currently no way to prevent the comment
  218. being saved once before removal) and, if the comment is still
  219. around, will send any notification emails the comment generated.
  220. """
  221. def __init__(self):
  222. self._registry = {}
  223. self.connect()
  224. def connect(self):
  225. """
  226. Hook up the moderation methods to pre- and post-save signals
  227. from the comment models.
  228. """
  229. signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model())
  230. signals.comment_was_posted.connect(self.post_save_moderation, sender=comments.get_model())
  231. def register(self, model_or_iterable, moderation_class):
  232. """
  233. Register a model or a list of models for comment moderation,
  234. using a particular moderation class.
  235. Raise ``AlreadyModerated`` if any of the models are already
  236. registered.
  237. """
  238. if isinstance(model_or_iterable, ModelBase):
  239. model_or_iterable = [model_or_iterable]
  240. for model in model_or_iterable:
  241. if model in self._registry:
  242. raise AlreadyModerated("The model '%s' is already being moderated" % model._meta.module_name)
  243. self._registry[model] = moderation_class(model)
  244. def unregister(self, model_or_iterable):
  245. """
  246. Remove a model or a list of models from the list of models
  247. whose comments will be moderated.
  248. Raise ``NotModerated`` if any of the models are not currently
  249. registered for moderation.
  250. """
  251. if isinstance(model_or_iterable, ModelBase):
  252. model_or_iterable = [model_or_iterable]
  253. for model in model_or_iterable:
  254. if model not in self._registry:
  255. raise NotModerated("The model '%s' is not currently being moderated" % model._meta.module_name)
  256. del self._registry[model]
  257. def pre_save_moderation(self, sender, comment, request, **kwargs):
  258. """
  259. Apply any necessary pre-save moderation steps to new
  260. comments.
  261. """
  262. model = comment.content_type.model_class()
  263. if model not in self._registry:
  264. return
  265. content_object = comment.content_object
  266. moderation_class = self._registry[model]
  267. # Comment will be disallowed outright (HTTP 403 response)
  268. if not moderation_class.allow(comment, content_object, request):
  269. return False
  270. if moderation_class.moderate(comment, content_object, request):
  271. comment.is_public = False
  272. def post_save_moderation(self, sender, comment, request, **kwargs):
  273. """
  274. Apply any necessary post-save moderation steps to new
  275. comments.
  276. """
  277. model = comment.content_type.model_class()
  278. if model not in self._registry:
  279. return
  280. self._registry[model].email(comment, comment.content_object, request)
  281. # Import this instance in your own code to use in registering
  282. # your models for moderation.
  283. moderator = Moderator()