]> git.openstreetmap.org Git - osqa.git/commitdiff
Some improvements in cache.
authorhernani <hernani@0cfe37f9-358a-4d5e-be75-b63607b5c754>
Mon, 24 May 2010 11:10:22 +0000 (11:10 +0000)
committerhernani <hernani@0cfe37f9-358a-4d5e-be75-b63607b5c754>
Mon, 24 May 2010 11:10:22 +0000 (11:10 +0000)
Convert answer to comment.
Fixed error user profile when editing date.

git-svn-id: http://svn.osqa.net/svnroot/osqa/trunk@315 0cfe37f9-358a-4d5e-be75-b63607b5c754

22 files changed:
forum/actions/meta.py
forum/actions/node.py
forum/models/action.py
forum/models/base.py
forum/models/node.py
forum/models/tag.py
forum/models/user.py
forum/settings/minrep.py
forum/skins/default/media/js/osqa.main.js
forum/skins/default/media/style/style.css
forum/skins/default/templates/_question_list.html [deleted file]
forum/skins/default/templates/node/convert_to_comment.html [new file with mode: 0644]
forum/skins/default/templates/node/post_controls.html
forum/skins/default/templates/node/report.html
forum/skins/default/templates/users/reputation.html
forum/templatetags/node_tags.py
forum/templatetags/user_tags.py
forum/urls.py
forum/views/admin.py
forum/views/commands.py
forum/views/users.py
forum_modules/pgfulltext/handlers.py

index 1862cb3113c04c2910e7bb0992958153ea5c8459..7c951101f8954885e1ed811b3561b65d47142d87 100644 (file)
@@ -27,6 +27,14 @@ class VoteAction(ActionProxy):
         except:\r
             return None\r
 \r
+    @classmethod\r
+    def get_action_for(cls, user, node):\r
+        try:\r
+            vote = Vote.objects.get(user=user, node=node)\r
+            return vote.action\r
+        except:\r
+            return None\r
+\r
     def describe_vote(self, vote_desc, viewer=None):\r
         return _("%(user)s %(vote_desc)s %(post_desc)s") % {\r
             'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),\r
@@ -183,9 +191,9 @@ class DeleteAction(ActionProxy):
             self.node.question.reset_answer_count_cache()\r
 \r
     def describe(self, viewer=None):\r
-        return _("%(user)s deleted %(post_desc)s: %(reason)s") % {\r
+        return _("%(user)s deleted %(post_desc)s") % {\r
             'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),\r
-            'post_desc': self.describe_node(viewer, self.node), 'reason': self.reason(),\r
+            'post_desc': self.describe_node(viewer, self.node)\r
         }\r
 \r
     def reason(self):\r
index 931b6e1ce4572788519bba7c2a639de5c59d557e..5283a8e98587feff199b64a2eed8c343e775dcf1 100644 (file)
@@ -148,4 +148,28 @@ class CloseAction(ActionProxy):
             'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),\r
             'post_desc': self.describe_node(viewer, self.node),\r
             'reason': self.extra\r
-        }
\ No newline at end of file
+        }\r
+\r
+class AnswerToCommentAction(ActionProxy):\r
+    verb = _("converted")\r
+\r
+    def process_data(self, new_parent=None):\r
+        self.node.parent = new_parent\r
+        self.node.node_type = "comment"\r
+\r
+        for comment in self.node.comments.all():\r
+            comment.parent = new_parent\r
+            comment.save()\r
+\r
+        self.node.save()\r
+        try:\r
+            self.node.abs_parent.reset_answer_count_cache()\r
+        except AttributeError:\r
+            pass\r
+\r
+    def describe(self, viewer=None):\r
+        return _("%(user)s converted an answer to %(question)s into a comment") % {\r
+            'user': self.hyperlink(self.user.get_profile_url(), self.friendly_username(viewer, self.user)),\r
+            'question': self.describe_node(viewer, self.node.abs_parent),\r
+        }\r
+\r
index 4eed471696b0dd172e1af903d8f3fdfbd46015cf..d892ac92658099b1a3f50a4ee63482076a7cff54 100644 (file)
@@ -4,18 +4,24 @@ from threading import Thread
 from base import *\r
 import re\r
 \r
-class ActionQuerySet(models.query.QuerySet):\r
+class ActionQuerySet(CachedQuerySet):\r
+    def obj_from_datadict(self, datadict):\r
+        cls = ActionProxyMetaClass.types.get(datadict['action_type'], None)\r
+        if cls:\r
+            obj = cls()\r
+            obj.__dict__.update(datadict)\r
+            return obj\r
+        else:\r
+            return super(ActionQuerySet, self).obj_from_datadict(datadict)\r
+\r
     def get(self, *args, **kwargs):\r
-        action = super(ActionQuerySet, self).get(*args, **kwargs)\r
-        if self.model == Action:\r
-            return action.leaf()\r
-        return action\r
+        return super(ActionQuerySet, self).get(*args, **kwargs).leaf()\r
 \r
-class ActionManager(models.Manager):\r
+class ActionManager(CachedManager):\r
     use_for_related_fields = True\r
 \r
     def get_query_set(self):\r
-        qs = ActionQuerySet(self.model).filter(canceled=False)\r
+        qs = ActionQuerySet(self.model)\r
 \r
         if self.model is not Action:\r
             return qs.filter(action_type=self.model.get_type())\r
@@ -26,7 +32,8 @@ class ActionManager(models.Manager):
         kwargs['action_type__in'] = [t.get_type() for t in types]\r
         return self.get(*args, **kwargs)\r
 \r
-class Action(models.Model):\r
+\r
+class Action(BaseModel):\r
     user = models.ForeignKey('User', related_name="actions")\r
     ip   = models.CharField(max_length=16)\r
     node = models.ForeignKey('Node', null=True, related_name="actions")\r
@@ -94,7 +101,9 @@ class Action(models.Model):
             return self\r
 \r
         leaf = leaf_cls()\r
-        leaf.__dict__ = self.__dict__\r
+        d = self._as_dict()\r
+        leaf.__dict__.update(self._as_dict())\r
+        l = leaf._as_dict()\r
         return leaf\r
 \r
     @classmethod\r
@@ -121,9 +130,9 @@ class Action(models.Model):
 \r
         return self\r
 \r
-    def delete(self):\r
+    def delete(self, *args, **kwargs):\r
         self.cancel_action()\r
-        super(Action, self).delete()\r
+        super(Action, self).delete(*args, **kwargs)\r
 \r
     def cancel(self, user=None, ip=None):\r
         if not self.canceled:\r
@@ -174,7 +183,7 @@ def trigger_hooks_threaded(action, hooks, new):
                 except Exception, e:\r
                     logging.error("Error in %s hook: %s" % (cls.__name__, str(e)))\r
 \r
-class ActionProxyMetaClass(models.Model.__metaclass__):\r
+class ActionProxyMetaClass(BaseMetaClass):\r
     types = {}\r
 \r
     def __new__(cls, *args, **kwargs):\r
index 827dfb26818c7a12e644ff2fd6c3945663a7b630..dfdf989fa305fa2fc41b30b277b44e2977ab6ff5 100644 (file)
@@ -40,6 +40,11 @@ class CachedQuerySet(models.query.QuerySet):
         else:
             return self
 
+    def obj_from_datadict(self, datadict):
+        obj = self.model()
+        obj.__dict__.update(datadict)
+        return obj
+
     def get(self, *args, **kwargs):
         try:
             pk = [v for (k,v) in kwargs.items() if k in ('pk', 'pk__exact', 'id', 'id__exact'
@@ -53,30 +58,21 @@ class CachedQuerySet(models.query.QuerySet):
 
             if obj is None:
                 obj = super(CachedQuerySet, self).get(*args, **kwargs)
-                obj.__class__.objects.cache_obj(obj)
+                obj.cache()
+            else:
+                obj = self.obj_from_datadict(obj)
+                obj.reset_original_state()
 
             return obj
 
         return super(CachedQuerySet, self).get(*args, **kwargs) 
 
-from action import Action
-
 class CachedManager(models.Manager):
     use_for_related_fields = True
-    int_cache_re = re.compile('^_[\w_]+cache$')
 
     def get_query_set(self):
         return CachedQuerySet(self.model)
 
-    def cache_obj(self, obj):
-        int_cache_keys = [k for k in obj.__dict__.keys() if self.int_cache_re.match(k)]
-        d = obj.__dict__
-        for k in int_cache_keys:
-            if not isinstance(obj.__dict__[k], Action):
-                del obj.__dict__[k]
-
-        cache.set(self.model.cache_key(obj.id), obj, 60 * 60)
-
     def get_or_create(self, *args, **kwargs):
         try:
             return self.get(*args, **kwargs)
@@ -90,7 +86,7 @@ class DenormalizedField(object):
         self.filter = kwargs
 
     def setup_class(self, cls, name):
-        dict_name = '_%s_cache_' % name
+        dict_name = '_%s_dencache_' % name
 
         def getter(inst):
             val = inst.__dict__.get(dict_name, None)
@@ -98,13 +94,13 @@ class DenormalizedField(object):
             if val is None:
                 val = getattr(inst, self.manager).filter(**self.filter).count()
                 inst.__dict__[dict_name] = val
-                inst.__class__.objects.cache_obj(inst)
+                inst.cache()
 
             return val
 
         def reset_cache(inst):
             inst.__dict__.pop(dict_name, None)
-            inst.__class__.objects.cache_obj(inst)
+            inst.uncache()
 
         cls.add_to_class(name, property(getter))
         cls.add_to_class("reset_%s_cache" % name, reset_cache)
@@ -139,20 +135,35 @@ class BaseModel(models.Model):
 
     def __init__(self, *args, **kwargs):
         super(BaseModel, self).__init__(*args, **kwargs)
-        self._original_state = dict([(k, v) for k,v in self.__dict__.items() if not k in kwargs])
+        self.reset_original_state()
 
     @classmethod
     def cache_key(cls, pk):
-        return '%s.%s:%s' % (settings.APP_URL, cls.__name__, pk)
+        return '%s:%s:%s' % (settings.APP_URL, cls.__name__, pk)
+
+    def reset_original_state(self):
+        self._original_state = self._as_dict()
 
     def get_dirty_fields(self):
-        missing = object()
-        return dict([(k, self._original_state.get(k, None)) for k,v in self.__dict__.items()
-                 if self._original_state.get(k, missing) == missing or self._original_state[k] != v])
+        return [f.name for f in self._meta.fields if self._original_state[f.attname] != self.__dict__[f.attname]]
+
+    def _as_dict(self):
+        return dict([(name, getattr(self, name)) for name in
+                     ([f.attname for f in self._meta.fields] + [k for k in self.__dict__.keys() if k.endswith('_dencache_')])
+        ])
+
+    def _get_update_kwargs(self):
+        return dict([
+            (f.name, getattr(self, f.name)) for f in self._meta.fields if self._original_state[f.attname] != self.__dict__[f.attname]
+        ])
 
     def save(self, *args, **kwargs):
         put_back = [k for k, v in self.__dict__.items() if isinstance(v, models.expressions.ExpressionNode)]
-        super(BaseModel, self).save()
+
+        if self.id:
+            self.__class__.objects.filter(id=self.id).update(**self._get_update_kwargs())
+        else:
+            super(BaseModel, self).save()
 
         if put_back:
             try:
@@ -163,115 +174,23 @@ class BaseModel(models.Model):
                 logging.error("Unable to read %s from %s" % (", ".join(put_back), self.__class__.__name__))
                 self.uncache()
 
-        self._original_state = dict(self.__dict__)
+        self.reset_original_state()
         self.cache()
 
     def cache(self):
-        self.__class__.objects.cache_obj(self)
+        cache.set(self.cache_key(self.id), self._as_dict(), 60 * 60)
 
     def uncache(self):
-        cache.delete(self.cache_key(self.pk))
+        cache.delete(self.cache_key(self.id))
 
     def delete(self):
         self.uncache()
         super(BaseModel, self).delete()
 
 
-class ActiveObjectManager(models.Manager):
-    use_for_related_fields = True
-    def get_query_set(self):
-        return super(ActiveObjectManager, self).get_query_set().filter(canceled=False)
-
-class UndeletedObjectManager(models.Manager):
-    def get_query_set(self):
-        return super(UndeletedObjectManager, self).get_query_set().filter(deleted=False)
-
-class GenericContent(models.Model):
-    content_type   = models.ForeignKey(ContentType)
-    object_id      = models.PositiveIntegerField()
-    content_object = generic.GenericForeignKey('content_type', 'object_id')
-
-    class Meta:
-        abstract = True
-        app_label = 'forum'
-
-class MetaContent(BaseModel):
-    node = models.ForeignKey('Node', null=True, related_name='%(class)ss')
-
-    def __init__(self, *args, **kwargs):
-        if 'content_object' in kwargs:
-            kwargs['node'] = kwargs['content_object']
-            del kwargs['content_object']
-
-        super (MetaContent, self).__init__(*args, **kwargs)
-    
-    @property
-    def content_object(self):
-        return self.node.leaf
-
-    class Meta:
-        abstract = True
-        app_label = 'forum'
-
 from user import User
-
-class UserContent(models.Model):
-    user = models.ForeignKey(User, related_name='%(class)ss')
-
-    class Meta:
-        abstract = True
-        app_label = 'forum'
-
-
-class DeletableContent(models.Model):
-    deleted     = models.BooleanField(default=False)
-    deleted_at  = models.DateTimeField(null=True, blank=True)
-    deleted_by  = models.ForeignKey(User, null=True, blank=True, related_name='deleted_%(class)ss')
-
-    active = UndeletedObjectManager()
-
-    class Meta:
-        abstract = True
-        app_label = 'forum'
-
-    def mark_deleted(self, user):
-        if not self.deleted:
-            self.deleted = True
-            self.deleted_at = datetime.datetime.now()
-            self.deleted_by = user
-            self.save()
-            return True
-        else:
-            return False
-
-    def unmark_deleted(self):
-        if self.deleted:
-            self.deleted = False
-            self.save()
-            return True
-        else:
-            return False
-
-mark_canceled = django.dispatch.Signal(providing_args=['instance'])
-
-class CancelableContent(models.Model):
-    canceled = models.BooleanField(default=False)
-
-    def cancel(self):
-        if not self.canceled:
-            self.canceled = True
-            self.save()
-            mark_canceled.send(sender=self.__class__, instance=self)
-            return True
-            
-        return False
-
-    class Meta:
-        abstract = True
-        app_label = 'forum'
-
-
 from node import Node, NodeRevision, NodeManager
+from action import Action
 
 
 
index 6f4e12b0429823bb4abad4d6243e18356e882c33..4be2a00557c21fca3a83c0b3217c90a9f9b7dc29 100644 (file)
@@ -79,13 +79,17 @@ class NodeMetaClass(BaseMetaClass):
 \r
 \r
 class NodeQuerySet(CachedQuerySet):\r
-    def get(self, *args, **kwargs):\r
-        node = super(NodeQuerySet, self).get(*args, **kwargs)\r
-        cls = NodeMetaClass.types.get(node.node_type, None)\r
+    def obj_from_datadict(self, datadict):\r
+        cls = NodeMetaClass.types.get(datadict.get("node_type", ""), None)\r
+        if cls:\r
+            obj = cls()\r
+            obj.__dict__.update(datadict)\r
+            return obj\r
+        else:\r
+            return super(NodeQuerySet, self).obj_from_datadict(datadict)\r
 \r
-        if cls and (node.__class__ is not cls):\r
-            return node.leaf\r
-        return node\r
+    def get(self, *args, **kwargs):\r
+        return super(NodeQuerySet, self).get(*args, **kwargs).leaf\r
 \r
 \r
 class NodeManager(CachedManager):\r
@@ -140,7 +144,7 @@ class Node(BaseModel, NodeContent):
 \r
     @classmethod\r
     def cache_key(cls, pk):\r
-        return '%s.node:%s' % (settings.APP_URL, pk)\r
+        return '%s:node:%s' % (settings.APP_URL, pk)\r
 \r
     @classmethod\r
     def get_type(cls):\r
@@ -209,8 +213,8 @@ class Node(BaseModel, NodeContent):
         if not 'tagnames' in dirty:\r
             return None\r
         else:\r
-            if dirty['tagnames']:\r
-                old_tags = set(name for name in dirty['tagnames'].split(u' '))\r
+            if self._original_state['tagnames']:\r
+                old_tags = set(name for name in self._original_state['tagnames'].split(u' '))\r
             else:\r
                 old_tags = set()\r
             new_tags = set(name for name in self.tagnames.split(u' ') if name)\r
@@ -269,6 +273,8 @@ class Node(BaseModel, NodeContent):
                 tag.save()\r
 \r
     def save(self, *args, **kwargs):\r
+        tags_changed = self._process_changes_in_tags()\r
+        \r
         if not self.id:\r
             self.node_type = self.get_type()\r
             super(BaseModel, self).save(*args, **kwargs)\r
@@ -278,8 +284,6 @@ class Node(BaseModel, NodeContent):
         if self.parent_id and not self.abs_parent_id:\r
             self.abs_parent = self.parent.absolute_parent\r
 \r
-        tags_changed = self._process_changes_in_tags()\r
-\r
         super(Node, self).save(*args, **kwargs)\r
         if tags_changed: self.tags = list(Tag.objects.filter(name__in=self.tagname_list()))\r
 \r
index 16f1c6cdc80a1699215d669f7984fd7dada35d9a..13445977ded256e0dc004d22e2a15fae787a23c8 100644 (file)
@@ -3,22 +3,45 @@ from base import *
 from django.utils.translation import ugettext as _
 import django.dispatch
 
-class ActiveTagManager(UndeletedObjectManager):
+class ActiveTagManager(models.Manager):
     def get_query_set(self):
-        return super(UndeletedObjectManager, self).get_query_set().exclude(used_count=0)
+        return super(ActiveTagManager, self).get_query_set().exclude(deleted=False, used_count=0)
 
 
-class Tag(BaseModel, DeletableContent):
+class Tag(BaseModel):
     name            = models.CharField(max_length=255, unique=True)
     created_by      = models.ForeignKey(User, related_name='created_tags')
     marked_by       = models.ManyToManyField(User, related_name="marked_tags", through="MarkedTag")
     # Denormalised data
     used_count = models.PositiveIntegerField(default=0)
 
+    deleted     = models.BooleanField(default=False)
+    deleted_at  = models.DateTimeField(null=True, blank=True)
+    deleted_by  = models.ForeignKey(User, null=True, blank=True, related_name='deleted_%(class)ss')
+
     active = ActiveTagManager()
 
-    class Meta(DeletableContent.Meta):
+    def mark_deleted(self, user):
+        if not self.deleted:
+            self.deleted = True
+            self.deleted_at = datetime.datetime.now()
+            self.deleted_by = user
+            self.save()
+            return True
+        else:
+            return False
+
+    def unmark_deleted(self):
+        if self.deleted:
+            self.deleted = False
+            self.save()
+            return True
+        else:
+            return False
+
+    class Meta:
         ordering = ('-used_count', 'name')
+        app_label = 'forum'
 
     def __unicode__(self):
         return self.name
index 3e92e1670c6d2fa548dfc4df184a2825fbce746b..c196bd44b74f7d5a0c39670f33f53fd12cfadaad 100644 (file)
@@ -55,12 +55,18 @@ class AnonymousUser(DjangoAnonymousUser):
     def can_delete_comment(self, comment):\r
         return False\r
 \r
+    def can_convert_to_comment(self, answer):\r
+        return False\r
+\r
     def can_accept_answer(self, answer):\r
         return False\r
 \r
     def can_edit_post(self, post):\r
         return False\r
 \r
+    def can_wikify(self, post):\r
+        return False\r
+\r
     def can_retag_questions(self):\r
         return False\r
 \r
@@ -201,6 +207,9 @@ class User(BaseModel, DjangoUser):
     def can_delete_comment(self, comment):\r
         return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)\r
 \r
+    def can_convert_to_comment(self, answer):\r
+        return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int(settings.REP_TO_CONVERT_TO_COMMENT))\r
+\r
     @true_if_is_super_or_staff\r
     def can_accept_answer(self, answer):\r
         return self == answer.question.author\r
@@ -210,6 +219,10 @@ class User(BaseModel, DjangoUser):
         return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS\r
         ) or (post.wiki and self.reputation >= int(settings.REP_TO_EDIT_WIKI))\r
 \r
+    @true_if_is_super_or_staff\r
+    def can_wikify(self, post):\r
+        return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)\r
+\r
     @true_if_is_super_or_staff\r
     def can_retag_questions(self):\r
         return self.reputation >= int(settings.REP_TO_RETAG)\r
index 7170a0355528a50218ae2fac65565af5c05c87cd..579215dd6194ce2a57a16ba73dfb82615f7afa1d 100644 (file)
@@ -43,6 +43,10 @@ REP_TO_EDIT_WIKI = Setting('REP_TO_EDIT_WIKI', 750, MIN_REP_SET, dict(
 label = _("Minimum reputation to edit wiki posts"),\r
 help_text = _("The minimum reputation an user must have to be allowed to edit community wiki posts.")))\r
 \r
+REP_TO_WIKIFY = Setting('REP_TO_WIKIFY', 2000, MIN_REP_SET, dict(\r
+label = _("Minimum reputation to mark post as community wiki"),\r
+help_text = _("The minimum reputation an user must have to be allowed to mark a post as community wiki.")))\r
+\r
 REP_TO_EDIT_OTHERS = Setting('REP_TO_EDIT_OTHERS', 2000, MIN_REP_SET, dict(\r
 label = _("Minimum reputation to edit others posts"),\r
 help_text = _("The minimum reputation an user must have to be allowed to edit others posts.")))\r
@@ -55,6 +59,10 @@ REP_TO_DELETE_COMMENTS = Setting('REP_TO_DELETE_COMMENTS', 2000, MIN_REP_SET, di
 label = _("Minimum reputation to delete comments"),\r
 help_text = _("The minimum reputation an user must have to be allowed to delete comments.")))\r
 \r
+REP_TO_CONVERT_TO_COMMENT = Setting('REP_TO_CONVERT_TO_COMMENT', 2000, MIN_REP_SET, dict(\r
+label = _("Minimum reputation to convert answers to comment"),\r
+help_text = _("The minimum reputation an user must have to be allowed to convert an answer into a comment.")))\r
+\r
 REP_TO_VIEW_FLAGS = Setting('REP_TO_VIEW_FLAGS', 2000, MIN_REP_SET, dict(\r
 label = _("Minimum reputation to view offensive flags"),\r
 help_text = _("The minimum reputation an user must have to view offensive flags.")))\r
index b5aee403eefdd95b373462b3c55c12ab4f3feb01..af80421ec51fc91b4ac3aad1afe08a4744e4ec2e 100644 (file)
@@ -229,10 +229,14 @@ function load_prompt(evt, url) {
     $.get(url, function(data) {\r
         var $dialog = show_dialog({\r
             html: data,\r
-            //extra_class: 'warning',\r
+            extra_class: 'prompt',\r
             event: evt,\r
             yes_callback: function() {\r
-                $.post(url, {prompt: $dialog.find('.prompt-return').val()}, function(data) {\r
+                var postvars = {};\r
+                $dialog.find('input, textarea, select').each(function() {\r
+                    postvars[$(this).attr('name')] = $(this).val();\r
+                });\r
+                $.post(url, postvars, function(data) {\r
                     $dialog.fadeOut('fast', function() {\r
                         $dialog.remove();\r
                     });\r
@@ -300,6 +304,22 @@ $(function() {
         return false\r
     });\r
 \r
+    $('.context-menu').each(function() {\r
+        var $menu = $(this);\r
+        var $trigger = $menu.find('.context-menu-trigger');\r
+        var $dropdown = $menu.find('.context-menu-dropdown');\r
+\r
+        $trigger.click(function() {\r
+            $dropdown.slideToggle('fast', function() {\r
+                if ($dropdown.is(':visible')) {\r
+                   $dropdown.one('clickoutside', function() {\r
+                        $dropdown.slideUp('fast')\r
+                    });\r
+                }\r
+            });    \r
+        });\r
+    });\r
+\r
     $('div.comment-form-container').each(function() {\r
         var $container = $(this);\r
         var $form = $container.find('form');\r
index 3084b55e66d3dbcf7bc1f7428d6e79dce3dd8200..a9d2072874c7973a0cfd3307732186b5e5cc5ac1 100644 (file)
@@ -1330,20 +1330,6 @@ div.comment-tools a:hover {
     background: url('/m/default/media/images/vote-accepted-on.png')
 }
 
-.user-prompt {
-    width: 300px;
-}
-
-.user-prompt select, .user-prompt textarea {
-    width: 100%;
-    padding: 0;
-    border: 0;
-}
-
-.user-prompt .prompt-buttons {
-    text-align: right;
-}
-
 .comment-form-buttons {
     width: 18%;
     height: 100%;
@@ -1373,7 +1359,11 @@ div.comment-tools a:hover {
     overflow-y: auto;
 }
 
-div.dialog {
+.context-menu {
+    position: relative;
+}
+
+div.dialog, .context-menu-dropdown {
     position: absolute;
     background-color: #EEEEEE;
     -moz-border-radius: 5px;
@@ -1382,6 +1372,49 @@ div.dialog {
     -webkit-box-shadow: 2px 2px 5px #3060A8;
 }
 
+.context-menu-dropdown {
+    display: none;
+    right: 0px;
+    top: 1.5em;
+    text-align: left;
+    list-style-type: none;
+}
+
+.context-menu-dropdown li.item {
+    padding: 4px 8px 4px 8px;
+     -moz-border-radius: 5px;
+    -webkit-border-radius: 5px;
+}
+
+.context-menu-dropdown li.item a {
+    color: inherit;
+    white-space: nowrap;
+    text-decoration: none;
+}
+
+.context-menu-dropdown li.separator {
+    text-align: center;
+    padding: 10px 0 4px 0;
+    font-size: 120%;
+    font-weight: bold;
+}
+
+.context-menu-dropdown li.item:hover {
+    background-color: #3060A8;
+    color: white;
+}
+
+.context-menu-dropdown span {
+    margin-right: 4px;
+    float: left;
+    width: 16px;
+    height: 16px;
+}
+
+.context-menu-trigger {
+    cursor: pointer;
+}
+
 div.dialog .dialog-content {
     padding: 12px 12px 37px 12px;
 }
@@ -1415,4 +1448,18 @@ div.dialog.confirm, div.dialog.warning {
 div.dialog.confirm {
     font-size: 140%;
     font-weight: bold;
+}
+
+div.dialog.prompt {
+    width: 300px;
+}
+
+div.dialog.prompt .dialog-content select, div.dialog.prompt .dialog-content textarea, div.dialog.prompt .dialog-content input[type=text] {
+    width: 100%;
+    padding: 0;
+    border: 0;
+}
+
+.user-prompt .prompt-buttons {
+    text-align: right;
 }
\ No newline at end of file
diff --git a/forum/skins/default/templates/_question_list.html b/forum/skins/default/templates/_question_list.html
deleted file mode 100644 (file)
index 02ef16d..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-{% load i18n %}\r
-{% load humanize %}\r
-{% load extra_filters %}\r
-{% load extra_tags %}\r
-\r
-<div id="listA">\r
-    {% for question in questions.object_list %}\r
-       <div class="short-summary">\r
-               <div class="counts">\r
-                       <div class="votes">\r
-                               <div class="item-count">{{question.score|intcomma}}</div>\r
-                               <div>{% trans "votes" %}</div>\r
-                       </div >\r
-                       <div {% if question.answer_accepted %}title="{% trans "this answer has been accepted to be correct" %}"{% endif %} class="status {% if question.answer_accepted %}answered-accepted{% endif %} {% ifequal question.answer_count 0 %}unanswered{% endifequal %}{% ifnotequal question.answer_count 0 %}answered{% endifnotequal %}">\r
-                               <div class="item-count">{{question.answer_count|intcomma}}</div>\r
-                               <div>{% trans "answers" %}</div>\r
-                       </div>\r
-                       <div class="views">\r
-                                <div class="item-count">{{question.view_count|cnprog_intword|safe}}</div>\r
-                                <div>{% trans "views" %}</div>\r
-                       </div>\r
-               </div>\r
-\r
-               <h2><a title="{{question.summary}}" href="{{ question.get_absolute_url }}">{{question.title}}</a></h2>\r
-               <div class="userinfo">\r
-                       <span class="relativetime" title="{{question.last_activity_at}}">{% diff_date question.last_activity_at %}</span>\r
-                       {% if question.last_activity_by %}\r
-                       <a href="/users/{{ question.last_activity_by.id }}/{{ question.last_activity_by.username|slugify }}/">{{ question.last_activity_by }}</a> {% get_score_badge question.last_activity_by %}\r
-                       {% endif %}\r
-               </div>\r
-\r
-               <div class="tags">\r
-                       {% for tag in question.tagname_list %}\r
-                       <a href="{% url tag_questions tag|urlencode %}" title="{% trans "see questions tagged" %} '{{ tag }}' {% trans "using tags" %}" rel="tag">{{ tag }}</a>\r
-                       {% endfor %}\r
-               </div>\r
-       </div>\r
-       {% endfor %}\r
-</div>
\ No newline at end of file
diff --git a/forum/skins/default/templates/node/convert_to_comment.html b/forum/skins/default/templates/node/convert_to_comment.html
new file mode 100644 (file)
index 0000000..cbaa4cd
--- /dev/null
@@ -0,0 +1,10 @@
+{% load i18n %}
+
+<div>
+    <p>{% trans "Place the comment under:" %}</p>
+    <select name="under">
+        {% for id, descr in nodes %}
+            <option value="{{ id }}">{{ descr }}</option>
+        {% endfor %}
+    </select>
+</div>                   
\ No newline at end of file
index c24660b29ad9965de6ff96064ee71b1b708596c8..9311e4b254221bedb3889efe6abe8c8fb75d8f25 100644 (file)
@@ -1,3 +1,4 @@
+{% load i18n %}\r
 {% spaceless %}\r
 {% for control in controls %}\r
     <span class="action-link">\r
@@ -8,4 +9,15 @@
         <span class="action-link-separator">|</span>\r
     {% endifnotequal %}\r
 {% endfor %}\r
+{% if menu|length %}\r
+    | <span id="node-{{ node.id }}-menu" class="context-menu">\r
+        <span id="node-{{ node.id }}-menu-trigger" class="context-menu-trigger">{% trans "more" %} &#9660;</span>\r
+        <ul id="node-{{ node.id }}-menu-dropdown" class="context-menu-dropdown">\r
+            {% for item in menu %}\r
+            <li class="item"><a class="{% if item.command %}ajax-command{% endif %}{% if item.withprompt %} withprompt{% endif %}"\r
+                href="{{ item.url }}" title="{{ item.title }}" >{{ item.text }}</a></li>\r
+            {% endfor %}\r
+        </ul>\r
+    </span>\r
+{% endif %}\r
 {% endspaceless %}
\ No newline at end of file
index c8607bbd30a14999568c0577b655e2be8137cc94..68b66d9ff2e600ec4dafc923f00d41596b15ce5f 100644 (file)
@@ -1,14 +1,12 @@
 {% load i18n %}\r
 \r
-<div class="user-prompt">\r
-    {% trans "Please select a reason bellow or use the text box to input your own reason." %}\r
-    <select class="prompt-examples">\r
-        {% for type in types %}\r
-            <option value="{{ type }}">{{ type }}</option>\r
-        {% endfor %}\r
-    </select>\r
-    <textarea class="prompt-return">{{ types|first }}</textarea>\r
-</div>\r
+{% trans "Please select a reason bellow or use the text box to input your own reason." %}\r
+<select class="prompt-examples">\r
+    {% for type in types %}\r
+        <option value="{{ type }}">{{ type }}</option>\r
+    {% endfor %}\r
+</select>\r
+<textarea name="prompt">{{ types|first }}</textarea>\r
 <script>\r
 $('.user-prompt .prompt-examples').change(function() {\r
     $('.user-prompt textarea').val($(this).val())            \r
index dfe5cd1dafb2dd959ee7bd6a1b6281f7f7459214..5b1559c8b47d6d11a2d48a8a486b787fec4279a9 100644 (file)
@@ -3,6 +3,7 @@
 {% load extra_tags %}
 {% load extra_filters %}
 {% load humanize %}
+{% load user_tags %}
 {% block userjs %}
        <script type='text/javascript' src='{% media  "/media/js/excanvas.min.js" %}'></script>
        <script type='text/javascript' src='{% media  "/media/js/jquery.flot.min.js" %}'></script>
@@ -34,7 +35,7 @@
                         <div style="float:left;width:20px;color:red">{{ rep.negative }}</div>
                         
                     </div>
-                    {{ rep.action.describe|safe }}<br/><span class="small">({{ rep.date }})</span>
+                    {% activity_item rep.action request.user %}<br/>
                 </p>
                 {% endfor %}
             </div>
index 72bfaf2a25939382ca634532e7e787fea030dd8d..454819437223e61bbe26b5c49ed3aaa3f625e265 100644 (file)
@@ -29,7 +29,7 @@ def accept_button(answer, user):
 @register.inclusion_tag('node/favorite_mark.html')\r
 def favorite_mark(question, user):\r
     try:\r
-        FavoriteAction.objects.get(node=question, user=user)\r
+        FavoriteAction.objects.get(canceled=False, node=question, user=user)\r
         favorited = True\r
     except:\r
         favorited = False\r
@@ -42,6 +42,7 @@ def post_control(text, url, command=False, withprompt=False, title=""):
 @register.inclusion_tag('node/post_controls.html')\r
 def post_controls(post, user):\r
     controls = []\r
+    menu = []\r
 \r
     if user.is_authenticated():\r
         post_type = (post.__class__ is Question) and 'question' or 'answer'\r
@@ -78,7 +79,15 @@ def post_controls(post, user):
                 controls.append(post_control(_('delete'), reverse('delete_post', kwargs={'id': post.id}),\r
                         command=True))\r
 \r
-    return {'controls': controls}\r
+        if user.can_wikify(post):\r
+            menu.append(post_control(_('mark as community wiki'), reverse('wikify', kwargs={'id': post.id}),\r
+                        command=True))\r
+\r
+        if post.node_type == "answer" and user.can_convert_to_comment(post):\r
+            menu.append(post_control(_('convert to comment'), reverse('convert_to_comment', kwargs={'id': post.id}),\r
+                        command=True, withprompt=True))\r
+\r
+    return {'controls': controls, 'menu': menu, 'post': post, 'user': user}\r
 \r
 @register.inclusion_tag('node/comments.html')\r
 def comments(post, user):\r
@@ -131,8 +140,8 @@ def contributors_info(node):
         'node': node,\r
     }\r
 \r
-\r
 @register.inclusion_tag("node/reviser_info.html")\r
 def reviser_info(revision):\r
     return {'revision': revision}\r
 \r
+\r
index d41cf479a0ff8d1ae177d753d8f49b874d2f8c32..b3f2bdf40242ec80f618458003273af99a9ae479 100644 (file)
@@ -42,6 +42,7 @@ class ActivityNode(template.Node):
             describe = mark_safe(action.describe(viewer))\r
             return self.template.render(template.Context(dict(action=action, describe=describe)))\r
         except Exception, e:\r
+            #return action.action_type + ":" + str(e)\r
             logging.error("Error in %s action describe: %s" % (action.action_type, str(e)))\r
 \r
 @register.tag\r
index 588c50d55bb2745b19778552594be8cceeccaf3c..00894ef41ff1dd624ec3b6a9cbe9355e55aba9c6 100644 (file)
@@ -73,9 +73,11 @@ urlpatterns += patterns('',
     url(r'^%s(?P<id>\d+)/$' % _('subscribe/'), app.commands.subscribe, name="subscribe"),
     url(r'^%s' % _('matching_tags/'), app.commands.matching_tags, name='matching_tags'),
     url(r'^%s(?P<id>\d+)/' % _('node_markdown/'), app.commands.node_markdown, name='node_markdown'),
+    url(r'^%s(?P<id>\d+)/' % _('convert/'), app.commands.convert_to_comment, name='convert_to_comment'),
+    url(r'^%s(?P<id>\d+)/' % _('wikify/'), app.commands.wikify, name='wikify'),
 
     #place general question item in the end of other operations
-    url(r'^%s(?P<id>\d+)/(?P<slug>[\w-]*)$' % _('question/'), app.readers.question, name='question'),
+    url(r'^%s(?P<id>\d+)/(?P<slug>[\w-]*)$' % _('questions/'), app.readers.question, name='question'),
     url(r'^%s$' % _('tags/'), app.readers.tags, name='tags'),
     url(r'^%s(?P<tag>.*)/$' % _('tags/'), app.readers.tag, name='tag_questions'),
 
index 543623de31b16217396d1c54ec6c30647acd9ef2..bfe8919721cc38db2c04b71753bc526e5a8cac34 100644 (file)
@@ -143,7 +143,7 @@ def get_recent_activity():
     return Action.objects.order_by('-action_date')[0:30]
 
 def get_flagged_posts():
-    return Action.objects.filter(action_type="flag").order_by('-action_date')[0:30]
+    return Action.objects.filter(canceled=False, action_type="flag").order_by('-action_date')[0:30]
 
 def get_statistics():
     return {
index e09924b064a38409874e253a66495263454d4fc9..1b3afc5ef3a3f8e0c014c34fe146697a9763e175 100644 (file)
@@ -7,6 +7,7 @@ from django.shortcuts import get_object_or_404, render_to_response
 from django.utils.translation import ungettext, ugettext as _
 from django.template import RequestContext
 from forum.models import *
+from forum.models.node import NodeMetaClass
 from forum.actions import *
 from django.core.urlresolvers import reverse
 from django.contrib.auth.decorators import login_required
@@ -69,9 +70,9 @@ def vote_post(request, id, vote_type):
     new_vote_cls = (vote_type == 'up') and VoteUpAction or VoteDownAction
     score_inc = 0
 
-    try:
-        old_vote = Action.objects.get_for_types((VoteUpAction, VoteDownAction), node=post, user=user)
+    old_vote = VoteAction.get_action_for(node=post, user=user)
 
+    if old_vote:
         if old_vote.action_date < datetime.datetime.now() - datetime.timedelta(days=int(settings.DENY_UNVOTE_DAYS)):
             raise CommandException(
                     _("Sorry but you cannot cancel a vote after %(ndays)d %(tdays)s from the original vote") %
@@ -80,8 +81,6 @@ def vote_post(request, id, vote_type):
 
         old_vote.cancel(ip=request.META['REMOTE_ADDR'])
         score_inc += (old_vote.__class__ == VoteDownAction) and 1 or -1
-    except ObjectDoesNotExist:
-        old_vote = None
 
     if old_vote.__class__ != new_vote_cls:
         new_vote_cls(user=user, node=post, ip=request.META['REMOTE_ADDR']).save()
@@ -127,7 +126,7 @@ def flag_post(request, id):
         raise NotEnoughLeftException(_('flags'), str(settings.MAX_FLAGS_PER_DAY))
 
     try:
-        current = FlagAction.objects.get(user=user, node=post)
+        current = FlagAction.objects.get(canceled=False, user=user, node=post)
         raise CommandException(_("You already flagged this post with the following reason: %(reason)s") % {'reason': current.extra})
     except ObjectDoesNotExist:
         reason = request.POST.get('prompt', '').strip()
@@ -153,11 +152,12 @@ def like_comment(request, id):
     if not user.can_like_comment(comment):
         raise NotEnoughRepPointsException( _('like comments'))    
 
-    try:
-        like = VoteUpCommentAction.objects.get(node=comment, user=user)
+    like = VoteAction.get_action_for(node=comment, user=user)
+
+    if like:
         like.cancel(ip=request.META['REMOTE_ADDR'])
         likes = False
-    except ObjectDoesNotExist:
+    else:
         VoteUpCommentAction(node=comment, user=user, ip=request.META['REMOTE_ADDR']).save()
         likes = True
 
@@ -196,7 +196,7 @@ def mark_favorite(request, id):
         raise AnonymousNotAllowedException(_('mark a question as favorite'))
 
     try:
-        favorite = FavoriteAction.objects.get(node=question, user=request.user)
+        favorite = FavoriteAction.objects.get(canceled=False, node=question, user=request.user)
         favorite.cancel(ip=request.META['REMOTE_ADDR'])
         added = False
     except ObjectDoesNotExist:
@@ -358,6 +358,45 @@ def close(request, id, close):
         }
     }
 
+@command
+def wikify(request, id):
+    pass
+
+@command
+def convert_to_comment(request, id):
+    user = request.user
+    answer = get_object_or_404(Answer, id=id)
+    question = answer.question
+
+    if not request.POST:
+        description = lambda a: _("Answer by %(uname)s: %(snippet)s...") % {'uname': a.author.username, 'snippet': a.summary[:10]}
+        nodes = [(question.id, _("Question"))]
+        [nodes.append((a.id, description(a))) for a in question.answers.filter(deleted=None).exclude(id=answer.id)]
+
+        return render_to_response('node/convert_to_comment.html', {'answer': answer, 'nodes': nodes})
+
+    if not user.is_authenticated():
+        raise AnonymousNotAllowedException(_("convert answers to comments"))
+
+    if not user.can_convert_to_comment(answer):
+        raise NotEnoughRepPointsException(_("convert answers to comments"))
+
+    try:
+        new_parent = Node.objects.get(id=request.POST.get('under', None))
+    except:
+        raise CommandException(_("That is an invalid post to put the comment under"))
+
+    if not (new_parent == question or (new_parent.node_type == 'answer' and new_parent.parent == question)):
+        raise CommandException(_("That is an invalid post to put the comment under"))
+
+    AnswerToCommentAction(user=user, node=answer, ip=request.META['REMOTE_ADDR']).save(data=dict(new_parent=new_parent))
+
+    return {
+        'commands': {
+            'refresh_page': []
+        }
+    }
+
 @command
 def subscribe(request, id):
     question = get_object_or_404(Question, id=id)
index 55a16099693250b4810c6e74a7f76f1da0b5e6f6..67f0a90c257aa2557a3cf4f970dbc94f24c6fb55 100644 (file)
@@ -15,7 +15,7 @@ from django.utils import simplejson
 from django.core.urlresolvers import reverse\r
 from forum.forms import *\r
 from forum.utils.html import sanitize_html\r
-from datetime import date\r
+from datetime import datetime, date\r
 import decorators\r
 from forum.actions import EditProfileAction, FavoriteAction, BonusRepAction\r
 \r
@@ -96,9 +96,9 @@ def edit_user(request, id):
             user.real_name = sanitize_html(form.cleaned_data['realname'])\r
             user.website = sanitize_html(form.cleaned_data['website'])\r
             user.location = sanitize_html(form.cleaned_data['city'])\r
-            user.date_of_birth = sanitize_html(form.cleaned_data['birthday'])\r
+            user.date_of_birth = form.cleaned_data['birthday']\r
             if user.date_of_birth == "None":\r
-                user.date_of_birth = '1900-01-01'\r
+                user.date_of_birth = datetime(1900, 1, 1, 0, 0)\r
             user.about = sanitize_html(form.cleaned_data['about'])\r
 \r
             user.save()\r
@@ -233,7 +233,7 @@ def user_reputation(request, user):
 \r
 @user_view('users/questions.html', 'favorites', _('favorite questions'),  _('favorite questions'))\r
 def user_favorites(request, user):\r
-    favorites = FavoriteAction.objects.filter(user=user)\r
+    favorites = FavoriteAction.objects.filter(canceled=False, user=user)\r
 \r
     return {"favorites" : favorites, "view_user" : user}\r
 \r
index 6e2165b247278613753a05367441e80c846931af..ff29f14823f7b8ac2db06aa7dba4bdda84c135c9 100644 (file)
@@ -4,19 +4,21 @@ from forum.modules.decorators import decorate
 
 @decorate(QuestionManager.search, needs_origin=False)
 def question_search(self, keywords):
+    tsquery = " | ".join(keywords.split(' '))
+    
     return self.extra(
                     tables = ['forum_rootnode_doc'],
                     select={
                         'ranking': """
-                                rank_exact_matches(ts_rank_cd('{0.1, 0.2, 0.8, 1.0}'::float4[], "forum_rootnode_doc"."document", plainto_tsquery('english', %s), 32))
+                                rank_exact_matches(ts_rank_cd('{0.1, 0.2, 0.8, 1.0}'::float4[], "forum_rootnode_doc"."document", to_tsquery('english', %s), 32))
                                 """,
                     },
                     where=["""
-                           "forum_rootnode_doc"."node_id" = "forum_node"."id" AND ("forum_rootnode_doc"."document" @@ plainto_tsquery('english', %s) OR
+                           "forum_rootnode_doc"."node_id" = "forum_node"."id" AND ("forum_rootnode_doc"."document" @@ to_tsquery('english', %s) OR
                            "forum_node"."title" ILIKE '""" + keywords + """%%')
                            """],
-                    params=[keywords],
-                    select_params=[keywords],
+                    params=[tsquery],
+                    select_params=[tsquery],
                     order_by=['-ranking']
                 )