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
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
'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
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
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
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
\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
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
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'
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)
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)
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)
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:
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
\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
\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
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
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
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
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
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
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
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
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
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
$.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
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
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%;
overflow-y: auto;
}
-div.dialog {
+.context-menu {
+ position: relative;
+}
+
+div.dialog, .context-menu-dropdown {
position: absolute;
background-color: #EEEEEE;
-moz-border-radius: 5px;
-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;
}
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
+++ /dev/null
-{% 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
--- /dev/null
+{% 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
+{% load i18n %}\r
{% spaceless %}\r
{% for control in controls %}\r
<span class="action-link">\r
<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" %} ▼</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
{% 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
{% 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>
<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>
@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
@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
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
'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
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
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'),
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 {
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
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") %
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()
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()
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
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:
}
}
+@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)
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
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
\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
@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']
)