6 from django.utils.translation import ugettext as _
7 from django.utils.safestring import mark_safe
8 from django.utils.html import strip_tags
9 from forum.utils.html import sanitize_html
10 from forum.settings import SUMMARY_LENGTH
11 from utils import PickledObjectField
13 class NodeContent(models.Model):
14 title = models.CharField(max_length=300)
15 tagnames = models.CharField(max_length=125)
16 author = models.ForeignKey(User, related_name='%(class)ss')
17 body = models.TextField()
28 def _as_markdown(cls, content, *extensions):
30 return mark_safe(sanitize_html(markdown.markdown(content, extensions=extensions)))
33 logging.error("Caught exception %s in markdown parser rendering %s %s:\s %s" % (
34 str(e), cls.__name__, str(e), traceback.format_exc()))
37 def as_markdown(self, *extensions):
38 return self._as_markdown(self.body, *extensions)
44 def tagname_list(self):
46 t = [name.strip() for name in self.tagnames.split(u' ') if name]
47 return [name.strip() for name in self.tagnames.split(u' ') if name]
51 def tagname_meta_generator(self):
52 return u','.join([tag for tag in self.tagname_list()])
58 class NodeMetaClass(BaseMetaClass):
61 def __new__(cls, *args, **kwargs):
62 new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
64 if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
65 NodeMetaClass.types[new_cls.get_type()] = new_cls
70 def setup_relations(cls):
71 for node_cls in NodeMetaClass.types.values():
72 NodeMetaClass.setup_relation(node_cls)
75 def setup_relation(cls, node_cls):
76 name = node_cls.__name__.lower()
79 return node_cls.objects.filter(parent=self)
82 if (self.parent is not None) and self.parent.node_type == name:
83 return self.parent.leaf
87 Node.add_to_class(name + 's', property(children))
88 Node.add_to_class(name, property(parent))
91 class NodeQuerySet(CachedQuerySet):
92 def obj_from_datadict(self, datadict):
93 cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)
96 obj.__dict__.update(datadict)
99 return super(NodeQuerySet, self).obj_from_datadict(datadict)
101 def get(self, *args, **kwargs):
102 node = super(NodeQuerySet, self).get(*args, **kwargs).leaf
104 if not isinstance(node, self.model):
105 raise self.model.DoesNotExist()
109 def any_state(self, *args):
113 s_filter = models.Q(state_string__contains="(%s)" % s)
114 filter = filter and (filter | s_filter) or s_filter
117 return self.filter(filter)
121 def all_states(self, *args):
125 s_filter = models.Q(state_string__contains="(%s)" % s)
126 filter = filter and (filter & s_filter) or s_filter
129 return self.filter(filter)
133 def filter_state(self, **kwargs):
134 apply_bool = lambda q, b: b and q or ~q
135 return self.filter(*[apply_bool(models.Q(state_string__contains="(%s)" % s), b) for s, b in kwargs.items()])
137 def children_count(self, child_type):
138 return NodeMetaClass.types[child_type].objects.filter_state(deleted=False).filter(parent__in=self).count()
141 class NodeManager(CachedManager):
142 use_for_related_fields = True
144 def get_query_set(self):
145 CurrentUserHolder = None
147 # We try to import from the moderation module.
149 moderation_import = 'from %s.moderation.startup import CurrentUserHolder' % MODULES_PACKAGE
150 exec moderation_import
152 moderation_enabled = True
154 moderation_enabled = False
156 qs = NodeQuerySet(self.model)
158 if self.model is not Node:
159 qs = qs.filter(node_type=self.model.get_type())
161 # If the moderation module has been enabled we make the filtration
162 if CurrentUserHolder is not None and moderation_enabled:
163 user = CurrentUserHolder.user
166 filter_content = not user.is_staff and not user.is_superuser
168 filter_content = True
171 qs = qs.exclude(state_string__contains="(in_moderation)").exclude(state_string__contains="(deleted)").exclude(
172 state_string__contains="(rejected)"
177 def get_for_types(self, types, *args, **kwargs):
178 kwargs['node_type__in'] = [t.get_type() for t in types]
179 return self.get(*args, **kwargs)
181 def filter_state(self, **kwargs):
182 return self.all().filter_state(**kwargs)
185 class NodeStateDict(object):
186 def __init__(self, node):
187 self.__dict__['_node'] = node
189 def __getattr__(self, name):
190 if self.__dict__.get(name, None):
191 return self.__dict__[name]
194 node = self.__dict__['_node']
195 action = NodeState.objects.get(node=node, state_type=name).action
196 self.__dict__[name] = action
201 def __setattr__(self, name, value):
202 current = self.__getattr__(name)
206 current.action = value
209 node = self.__dict__['_node']
210 state = NodeState(node=node, action=value, state_type=name)
212 self.__dict__[name] = value
214 if not "(%s)" % name in node.state_string:
215 node.state_string = "%s(%s)" % (node.state_string, name)
219 node = self.__dict__['_node']
220 node.state_string = "".join("(%s)" % s for s in re.findall('\w+', node.state_string) if s != name)
222 current.node_state.delete()
223 del self.__dict__[name]
226 class NodeStateQuery(object):
227 def __init__(self, node):
228 self.__dict__['_node'] = node
230 def __getattr__(self, name):
231 node = self.__dict__['_node']
232 return "(%s)" % name in node.state_string
235 class Node(BaseModel, NodeContent):
236 __metaclass__ = NodeMetaClass
238 node_type = models.CharField(max_length=16, default='node')
239 parent = models.ForeignKey('Node', related_name='children', null=True)
240 abs_parent = models.ForeignKey('Node', related_name='all_children', null=True)
242 added_at = models.DateTimeField(default=datetime.datetime.now)
243 score = models.IntegerField(default=0)
245 state_string = models.TextField(default='')
246 last_edited = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
248 last_activity_by = models.ForeignKey(User, null=True)
249 last_activity_at = models.DateTimeField(null=True, blank=True)
251 tags = models.ManyToManyField('Tag', related_name='%(class)ss')
252 active_revision = models.OneToOneField('NodeRevision', related_name='active', null=True)
254 extra = PickledObjectField()
255 extra_ref = models.ForeignKey('Node', null=True)
256 extra_count = models.IntegerField(default=0)
258 marked = models.BooleanField(default=False)
260 comment_count = DenormalizedField("children", node_type="comment", canceled=False)
261 flag_count = DenormalizedField("flags")
263 friendly_name = _("post")
265 objects = NodeManager()
267 def __unicode__(self):
271 def _generate_cache_key(cls, key, group="node"):
272 return super(Node, cls)._generate_cache_key(key, group)
276 return cls.__name__.lower()
280 leaf_cls = NodeMetaClass.types.get(self.node_type, None)
286 leaf.__dict__ = self.__dict__
291 state = self.__dict__.get('_nstate', None)
294 state = NodeStateDict(self)
301 nis = self.__dict__.get('_nis', None)
304 nis = NodeStateQuery(self)
310 def last_activity(self):
312 return self.actions.order_by('-action_date')[0].action_date
314 return self.last_seen
317 def state_list(self):
318 return [s.state_type for s in self.states.all()]
322 return self.nis.deleted
325 def absolute_parent(self):
326 if not self.abs_parent_id:
329 return self.abs_parent
333 return strip_tags(self.html)[:SUMMARY_LENGTH]
336 def get_revisions_url(self):
337 return ('revisions', (), {'id': self.id})
339 def update_last_activity(self, user, save=False, time=None):
341 time = datetime.datetime.now()
343 self.last_activity_by = user
344 self.last_activity_at = time
347 self.parent.update_last_activity(user, save=True, time=time)
352 def _create_revision(self, user, number, **kwargs):
353 revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
357 def create_revision(self, user, **kwargs):
358 number = self.revisions.aggregate(last=models.Max('revision'))['last'] + 1
359 revision = self._create_revision(user, number, **kwargs)
360 self.activate_revision(user, revision, extensions=['urlize'])
363 def activate_revision(self, user, revision, extensions=['urlize']):
364 self.title = revision.title
365 self.tagnames = revision.tagnames
367 from forum.utils.userlinking import auto_user_link
369 self.body = auto_user_link(self, self._as_markdown(revision.body, *extensions))
371 self.active_revision = revision
372 self.update_last_activity(user)
376 def _list_changes_in_tags(self):
377 dirty = self.get_dirty_fields()
379 if not 'tagnames' in dirty:
382 if self._original_state['tagnames']:
383 old_tags = set(name for name in self._original_state['tagnames'].split(u' '))
386 new_tags = set(name for name in self.tagnames.split(u' ') if name)
389 current=list(new_tags),
390 added=list(new_tags - old_tags),
391 removed=list(old_tags - new_tags)
394 def _last_active_user(self):
395 return self.last_edited and self.last_edited.by or self.author
397 def _process_changes_in_tags(self):
398 tag_changes = self._list_changes_in_tags()
400 if tag_changes is not None:
401 for name in tag_changes['added']:
403 tag = Tag.objects.get(name=name)
405 tag = Tag.objects.create(name=name, created_by=self._last_active_user())
407 if not self.nis.deleted:
408 tag.add_to_usage_count(1)
411 if not self.nis.deleted:
412 for name in tag_changes['removed']:
414 tag = Tag.objects.get(name=name)
415 tag.add_to_usage_count(-1)
424 def mark_deleted(self, action):
425 self.nstate.deleted = action
429 for tag in self.tags.all():
430 tag.add_to_usage_count(-1)
433 for tag in Tag.objects.filter(name__in=self.tagname_list()):
434 tag.add_to_usage_count(1)
437 def delete(self, *args, **kwargs):
438 self.active_revision = None
441 for n in self.children.all():
444 for a in self.actions.all():
447 super(Node, self).delete(*args, **kwargs)
449 def save(self, *args, **kwargs):
451 self.node_type = self.get_type()
452 super(BaseModel, self).save(*args, **kwargs)
453 self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
455 self.activate_revision(self.author, self.active_revision)
456 self.update_last_activity(self.author, time=self.added_at)
458 if self.parent_id and not self.abs_parent_id:
459 self.abs_parent = self.parent.absolute_parent
461 tags_changed = self._process_changes_in_tags()
463 super(Node, self).save(*args, **kwargs)
465 if tags_changed: self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
471 class NodeRevision(BaseModel, NodeContent):
472 node = models.ForeignKey(Node, related_name='revisions')
473 summary = models.CharField(max_length=300)
474 revision = models.PositiveIntegerField()
475 revised_at = models.DateTimeField(default=datetime.datetime.now)
478 unique_together = ('node', 'revision')
482 class NodeState(models.Model):
483 node = models.ForeignKey(Node, related_name='states')
484 state_type = models.CharField(max_length=16)
485 action = models.OneToOneField('Action', related_name="node_state")
488 unique_together = ('node', 'state_type')