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 forum.modules import MODULES_PACKAGE
12 from utils import PickledObjectField
14 class NodeContent(models.Model):
15 title = models.CharField(max_length=300)
16 tagnames = models.CharField(max_length=125)
17 author = models.ForeignKey(User, related_name='%(class)ss')
18 body = models.TextField()
29 def _as_markdown(cls, content, *extensions):
31 return mark_safe(sanitize_html(markdown.markdown(content, extensions=extensions)))
34 logging.error("Caught exception %s in markdown parser rendering %s %s:\s %s" % (
35 str(e), cls.__name__, str(e), traceback.format_exc()))
38 def as_markdown(self, *extensions):
39 return self._as_markdown(self.body, *extensions)
45 def tagname_list(self):
47 t = [name.strip() for name in self.tagnames.split(u' ') if name]
48 return [name.strip() for name in self.tagnames.split(u' ') if name]
52 def tagname_meta_generator(self):
53 return u','.join([tag for tag in self.tagname_list()])
59 class NodeMetaClass(BaseMetaClass):
62 def __new__(cls, *args, **kwargs):
63 new_cls = super(NodeMetaClass, cls).__new__(cls, *args, **kwargs)
65 if not new_cls._meta.abstract and new_cls.__name__ is not 'Node':
66 NodeMetaClass.types[new_cls.get_type()] = new_cls
71 def setup_relations(cls):
72 for node_cls in NodeMetaClass.types.values():
73 NodeMetaClass.setup_relation(node_cls)
76 def setup_relation(cls, node_cls):
77 name = node_cls.__name__.lower()
80 return node_cls.objects.filter(parent=self)
83 if (self.parent is not None) and self.parent.node_type == name:
84 return self.parent.leaf
88 Node.add_to_class(name + 's', property(children))
89 Node.add_to_class(name, property(parent))
92 class NodeQuerySet(CachedQuerySet):
93 def obj_from_datadict(self, datadict):
94 cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)
97 obj.__dict__.update(datadict)
100 return super(NodeQuerySet, self).obj_from_datadict(datadict)
102 def get(self, *args, **kwargs):
103 node = super(NodeQuerySet, self).get(*args, **kwargs).leaf
105 if not isinstance(node, self.model):
106 raise self.model.DoesNotExist()
110 def any_state(self, *args):
114 s_filter = models.Q(state_string__contains="(%s)" % s)
115 filter = filter and (filter | s_filter) or s_filter
118 return self.filter(filter)
122 def all_states(self, *args):
126 s_filter = models.Q(state_string__contains="(%s)" % s)
127 filter = filter and (filter & s_filter) or s_filter
130 return self.filter(filter)
134 def filter_state(self, **kwargs):
135 apply_bool = lambda q, b: b and q or ~q
136 return self.filter(*[apply_bool(models.Q(state_string__contains="(%s)" % s), b) for s, b in kwargs.items()])
138 def children_count(self, child_type):
139 return NodeMetaClass.types[child_type].objects.filter_state(deleted=False).filter(parent__in=self).count()
142 class NodeManager(CachedManager):
143 use_for_related_fields = True
145 def get_query_set(self):
146 CurrentUserHolder = None
148 moderation_import = 'from %s.moderation.startup import CurrentUserHolder' % MODULES_PACKAGE
149 exec moderation_import
151 qs = NodeQuerySet(self.model)
153 if self.model is not Node:
154 qs = qs.filter(node_type=self.model.get_type())
156 if CurrentUserHolder is not None:
157 user = CurrentUserHolder.user
160 filter_content = not user.is_staff and not user.is_superuser
162 filter_content = True
165 qs = qs.exclude(state_string__contains="(in_moderation)").exclude(state_string__contains="(deleted)").exclude(
166 state_string__contains="(rejected)"
171 def get_for_types(self, types, *args, **kwargs):
172 kwargs['node_type__in'] = [t.get_type() for t in types]
173 return self.get(*args, **kwargs)
175 def filter_state(self, **kwargs):
176 return self.all().filter_state(**kwargs)
179 class NodeStateDict(object):
180 def __init__(self, node):
181 self.__dict__['_node'] = node
183 def __getattr__(self, name):
184 if self.__dict__.get(name, None):
185 return self.__dict__[name]
188 node = self.__dict__['_node']
189 action = NodeState.objects.get(node=node, state_type=name).action
190 self.__dict__[name] = action
195 def __setattr__(self, name, value):
196 current = self.__getattr__(name)
200 current.action = value
203 node = self.__dict__['_node']
204 state = NodeState(node=node, action=value, state_type=name)
206 self.__dict__[name] = value
208 if not "(%s)" % name in node.state_string:
209 node.state_string = "%s(%s)" % (node.state_string, name)
213 node = self.__dict__['_node']
214 node.state_string = "".join("(%s)" % s for s in re.findall('\w+', node.state_string) if s != name)
216 current.node_state.delete()
217 del self.__dict__[name]
220 class NodeStateQuery(object):
221 def __init__(self, node):
222 self.__dict__['_node'] = node
224 def __getattr__(self, name):
225 node = self.__dict__['_node']
226 return "(%s)" % name in node.state_string
229 class Node(BaseModel, NodeContent):
230 __metaclass__ = NodeMetaClass
232 node_type = models.CharField(max_length=16, default='node')
233 parent = models.ForeignKey('Node', related_name='children', null=True)
234 abs_parent = models.ForeignKey('Node', related_name='all_children', null=True)
236 added_at = models.DateTimeField(default=datetime.datetime.now)
237 score = models.IntegerField(default=0)
239 state_string = models.TextField(default='')
240 last_edited = models.ForeignKey('Action', null=True, unique=True, related_name="edited_node")
242 last_activity_by = models.ForeignKey(User, null=True)
243 last_activity_at = models.DateTimeField(null=True, blank=True)
245 tags = models.ManyToManyField('Tag', related_name='%(class)ss')
246 active_revision = models.OneToOneField('NodeRevision', related_name='active', null=True)
248 extra = PickledObjectField()
249 extra_ref = models.ForeignKey('Node', null=True)
250 extra_count = models.IntegerField(default=0)
252 marked = models.BooleanField(default=False)
254 comment_count = DenormalizedField("children", node_type="comment", canceled=False)
255 flag_count = DenormalizedField("flags")
257 friendly_name = _("post")
259 objects = NodeManager()
261 def __unicode__(self):
265 def _generate_cache_key(cls, key, group="node"):
266 return super(Node, cls)._generate_cache_key(key, group)
270 return cls.__name__.lower()
274 leaf_cls = NodeMetaClass.types.get(self.node_type, None)
280 leaf.__dict__ = self.__dict__
285 state = self.__dict__.get('_nstate', None)
288 state = NodeStateDict(self)
295 nis = self.__dict__.get('_nis', None)
298 nis = NodeStateQuery(self)
304 def last_activity(self):
306 return self.actions.order_by('-action_date')[0].action_date
308 return self.last_seen
311 def state_list(self):
312 return [s.state_type for s in self.states.all()]
316 return self.nis.deleted
319 def absolute_parent(self):
320 if not self.abs_parent_id:
323 return self.abs_parent
327 return strip_tags(self.html)[:SUMMARY_LENGTH]
330 def get_revisions_url(self):
331 return ('revisions', (), {'id': self.id})
333 def update_last_activity(self, user, save=False, time=None):
335 time = datetime.datetime.now()
337 self.last_activity_by = user
338 self.last_activity_at = time
341 self.parent.update_last_activity(user, save=True, time=time)
346 def _create_revision(self, user, number, **kwargs):
347 revision = NodeRevision(author=user, revision=number, node=self, **kwargs)
351 def create_revision(self, user, **kwargs):
352 number = self.revisions.aggregate(last=models.Max('revision'))['last'] + 1
353 revision = self._create_revision(user, number, **kwargs)
354 self.activate_revision(user, revision, extensions=['urlize'])
357 def activate_revision(self, user, revision, extensions=['urlize']):
358 self.title = revision.title
359 self.tagnames = revision.tagnames
361 from forum.utils.userlinking import auto_user_link
363 self.body = auto_user_link(self, self._as_markdown(revision.body, *extensions))
365 self.active_revision = revision
366 self.update_last_activity(user)
370 def _list_changes_in_tags(self):
371 dirty = self.get_dirty_fields()
373 if not 'tagnames' in dirty:
376 if self._original_state['tagnames']:
377 old_tags = set(name for name in self._original_state['tagnames'].split(u' '))
380 new_tags = set(name for name in self.tagnames.split(u' ') if name)
383 current=list(new_tags),
384 added=list(new_tags - old_tags),
385 removed=list(old_tags - new_tags)
388 def _last_active_user(self):
389 return self.last_edited and self.last_edited.by or self.author
391 def _process_changes_in_tags(self):
392 tag_changes = self._list_changes_in_tags()
394 if tag_changes is not None:
395 for name in tag_changes['added']:
397 tag = Tag.objects.get(name=name)
399 tag = Tag.objects.create(name=name, created_by=self._last_active_user())
401 if not self.nis.deleted:
402 tag.add_to_usage_count(1)
405 if not self.nis.deleted:
406 for name in tag_changes['removed']:
408 tag = Tag.objects.get(name=name)
409 tag.add_to_usage_count(-1)
418 def mark_deleted(self, action):
419 self.nstate.deleted = action
423 for tag in self.tags.all():
424 tag.add_to_usage_count(-1)
427 for tag in Tag.objects.filter(name__in=self.tagname_list()):
428 tag.add_to_usage_count(1)
431 def delete(self, *args, **kwargs):
432 self.active_revision = None
435 for n in self.children.all():
438 for a in self.actions.all():
441 super(Node, self).delete(*args, **kwargs)
443 def save(self, *args, **kwargs):
445 self.node_type = self.get_type()
446 super(BaseModel, self).save(*args, **kwargs)
447 self.active_revision = self._create_revision(self.author, 1, title=self.title, tagnames=self.tagnames,
449 self.activate_revision(self.author, self.active_revision)
450 self.update_last_activity(self.author, time=self.added_at)
452 if self.parent_id and not self.abs_parent_id:
453 self.abs_parent = self.parent.absolute_parent
455 tags_changed = self._process_changes_in_tags()
457 super(Node, self).save(*args, **kwargs)
459 if tags_changed: self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))
465 class NodeRevision(BaseModel, NodeContent):
466 node = models.ForeignKey(Node, related_name='revisions')
467 summary = models.CharField(max_length=300)
468 revision = models.PositiveIntegerField()
469 revised_at = models.DateTimeField(default=datetime.datetime.now)
472 unique_together = ('node', 'revision')
476 class NodeState(models.Model):
477 node = models.ForeignKey(Node, related_name='states')
478 state_type = models.CharField(max_length=16)
479 action = models.OneToOneField('Action', related_name="node_state")
482 unique_together = ('node', 'state_type')