2 from utils import PickledObjectField
3 from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
4 from django.contrib.contenttypes.models import ContentType
5 from django.contrib.auth.models import User as DjangoUser, AnonymousUser as DjangoAnonymousUser
6 from django.db.models import Q
8 from django.utils.encoding import smart_unicode
10 from forum.settings import TRUNCATE_LONG_USERNAMES, TRUNCATE_USERNAMES_LONGER_THAN
13 from random import Random
15 from django.utils.translation import ugettext as _
18 class AnonymousUser(DjangoAnonymousUser):
21 def get_visible_answers(self, question):
22 return question.answers.filter_state(deleted=False)
24 def can_view_deleted_post(self, post):
27 def can_vote_up(self):
30 def can_vote_down(self):
33 def can_vote_count_today(self):
36 def can_flag_offensive(self, post=None):
39 def can_view_offensive_flags(self, post=None):
42 def can_comment(self, post):
45 def can_like_comment(self, comment):
48 def can_edit_comment(self, comment):
51 def can_delete_comment(self, comment):
54 def can_convert_to_comment(self, answer):
57 def can_convert_to_question(self, answer):
60 def can_convert_comment_to_answer(self, comment):
63 def can_accept_answer(self, answer):
66 def can_create_tags(self):
69 def can_edit_post(self, post):
72 def can_wikify(self, post):
75 def can_cancel_wiki(self, post):
78 def can_retag_questions(self):
81 def can_close_question(self, question):
84 def can_reopen_question(self, question):
87 def can_delete_post(self, post):
90 def can_upload_files(self):
93 def is_a_super_user_or_staff(self):
96 def true_if_is_super_or_staff(fn):
97 def decorated(self, *args, **kwargs):
98 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
102 def false_if_validation_required_to(item):
104 def decorated(self, *args, **kwargs):
105 if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
108 return fn(self, *args, **kwargs)
112 class User(BaseModel, DjangoUser):
113 is_approved = models.BooleanField(default=False)
114 email_isvalid = models.BooleanField(default=False)
116 reputation = models.IntegerField(default=0)
117 gold = models.PositiveIntegerField(default=0)
118 silver = models.PositiveIntegerField(default=0)
119 bronze = models.PositiveIntegerField(default=0)
121 last_seen = models.DateTimeField(default=datetime.datetime.now)
122 real_name = models.CharField(max_length=100, blank=True)
123 website = models.URLField(max_length=200, blank=True)
124 location = models.CharField(max_length=100, blank=True)
125 date_of_birth = models.DateField(null=True, blank=True)
126 about = models.TextField(blank=True)
128 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
130 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
131 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
133 def __unicode__(self):
134 return smart_unicode(self.username)
138 prop = self.__dict__.get('_prop', None)
141 prop = UserPropertyDict(self)
147 def is_siteowner(self):
148 #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
152 def decorated_name(self):
153 username = smart_unicode(self.username)
155 if len(username) > TRUNCATE_USERNAMES_LONGER_THAN and TRUNCATE_LONG_USERNAMES:
156 username = '%s...' % username[:TRUNCATE_USERNAMES_LONGER_THAN-3]
158 if settings.SHOW_STATUS_DIAMONDS:
159 if self.is_superuser:
160 return u"%s \u2666\u2666" % username
163 return u"%s \u2666" % username
168 def last_activity(self):
170 return self.actions.order_by('-action_date')[0].action_date
172 return self.last_seen
176 return md5(self.email.lower()).hexdigest()
178 def save(self, *args, **kwargs):
179 # If the community doesn't allow negative reputation, set it to 0
180 if not settings.ALLOW_NEGATIVE_REPUTATION and self.reputation < 0:
183 new = not bool(self.id)
185 super(User, self).save(*args, **kwargs)
188 sub_settings = SubscriptionSettings(user=self)
191 def get_messages(self):
193 for m in self.message_set.all():
194 messages.append(m.message)
197 def delete_messages(self):
198 self.message_set.all().delete()
201 def get_profile_url(self):
202 return ('user_profile', (), {'id': self.id, 'slug': slugify(smart_unicode(self.username))})
204 def get_absolute_url(self):
205 return self.get_profile_url()
208 def get_asked_url(self):
209 return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
212 def get_user_subscriptions_url(self):
213 return ('user_subscriptions', (), { 'id': self.id, 'slug': slugify(smart_unicode(self.username))})
216 def get_answered_url(self):
217 return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
219 def get_subscribed_url(self):
221 # Try to retrieve the Subscribed User URL.
222 url = reverse('user_questions',
223 kwargs={'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
226 # If some Exception has been raised, don't forget to log it.
227 logging.error("Error retrieving a subscribed user URL: %s" % e)
229 def get_profile_link(self):
230 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
231 return mark_safe(profile_link)
233 def get_visible_answers(self, question):
234 return question.answers.filter_state(deleted=False)
236 def get_vote_count_today(self):
237 today = datetime.date.today()
238 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
239 action_date__gte=(today - datetime.timedelta(days=1))).count()
241 def get_reputation_by_upvoted_today(self):
242 today = datetime.datetime.now()
243 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
245 #todo: redo this, maybe transform in the daily cap
246 #if sum.get('value__sum', None) is not None: return sum['value__sum']
249 def get_flagged_items_count_today(self):
250 today = datetime.date.today()
251 return self.actions.filter(canceled=False, action_type="flag",
252 action_date__gte=(today - datetime.timedelta(days=1))).count()
254 def can_vote_count_today(self):
255 votes_today = settings.MAX_VOTES_PER_DAY
257 if settings.USER_REPUTATION_TO_MAX_VOTES:
258 votes_today = votes_today + int(self.reputation)
262 @true_if_is_super_or_staff
263 def can_view_deleted_post(self, post):
264 return post.author == self
266 @true_if_is_super_or_staff
267 def can_vote_up(self):
268 return self.reputation >= int(settings.REP_TO_VOTE_UP)
270 @true_if_is_super_or_staff
271 def can_vote_down(self):
272 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
274 @false_if_validation_required_to('flag')
275 def can_flag_offensive(self, post=None):
276 if post is not None and post.author == self:
278 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
280 @true_if_is_super_or_staff
281 def can_view_offensive_flags(self, post=None):
282 if post is not None and post.author == self:
284 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
286 @true_if_is_super_or_staff
287 @false_if_validation_required_to('comment')
288 def can_comment(self, post):
289 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
290 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
292 @true_if_is_super_or_staff
293 def can_like_comment(self, comment):
294 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
296 @true_if_is_super_or_staff
297 def can_edit_comment(self, comment):
298 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
299 ) or self.is_superuser
301 @true_if_is_super_or_staff
302 def can_delete_comment(self, comment):
303 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
305 def can_convert_comment_to_answer(self, comment):
306 # We need to know what is the comment parent node type.
307 comment_parent_type = comment.parent.node_type
309 # If the parent is not a question or an answer this comment cannot be converted to an answer.
310 if comment_parent_type != "question" and comment_parent_type != "answer":
313 return (comment.parent.node_type in ('question', 'answer')) and (self.is_superuser or self.is_staff or (
314 self == comment.author) or (self.reputation >= int(settings.REP_TO_CONVERT_COMMENTS_TO_ANSWERS)))
316 def can_convert_to_comment(self, answer):
317 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
318 (settings.REP_TO_CONVERT_TO_COMMENT))
320 def can_convert_to_question(self, node):
321 return (not node.marked) and (self.is_superuser or self.is_staff or node.author == self or self.reputation >= int
322 (settings.REP_TO_CONVERT_TO_QUESTION))
324 @true_if_is_super_or_staff
325 def can_accept_answer(self, answer):
326 return self == answer.question.author and (settings.USERS_CAN_ACCEPT_OWN or answer.author != answer.question.author)
328 @true_if_is_super_or_staff
329 def can_create_tags(self):
330 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
332 @true_if_is_super_or_staff
333 def can_edit_post(self, post):
334 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
335 ) or (post.nis.wiki and self.reputation >= int(
336 settings.REP_TO_EDIT_WIKI))
338 @true_if_is_super_or_staff
339 def can_wikify(self, post):
340 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
342 @true_if_is_super_or_staff
343 def can_cancel_wiki(self, post):
344 return self == post.author
346 @true_if_is_super_or_staff
347 def can_retag_questions(self):
348 return self.reputation >= int(settings.REP_TO_RETAG)
350 @true_if_is_super_or_staff
351 def can_close_question(self, question):
352 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
353 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
355 @true_if_is_super_or_staff
356 def can_reopen_question(self, question):
357 return self == question.author and self.reputation >= int(settings.REP_TO_REOPEN_OWN)
359 @true_if_is_super_or_staff
360 def can_delete_post(self, post):
361 if post.node_type == "comment":
362 return self.can_delete_comment(post)
364 return (self == post.author and (post.__class__.__name__ == "Answer" or
365 not post.answers.exclude(author__id=self.id).count()))
367 @true_if_is_super_or_staff
368 def can_upload_files(self):
369 return self.reputation >= int(settings.REP_TO_UPLOAD)
371 @true_if_is_super_or_staff
372 def is_a_super_user_or_staff(self):
375 def email_valid_and_can_ask(self):
376 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
378 def email_valid_and_can_answer(self):
379 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
381 def check_password(self, old_passwd):
382 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
383 return DjangoUser.check_password(self, old_passwd)
386 def suspension(self):
387 if self.__dict__.get('_suspension_dencache_', False) != None:
389 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
390 except ObjectDoesNotExist:
391 self.__dict__['_suspension_dencache_'] = None
392 except MultipleObjectsReturned:
393 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
394 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
395 ).order_by('-action__action_date')[0]
397 return self.__dict__['_suspension_dencache_']
399 def _pop_suspension_cache(self):
400 self.__dict__.pop('_suspension_dencache_', None)
402 def is_suspended(self):
403 if not self.is_active:
404 suspension = self.suspension
406 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
407 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
408 days=int(suspension.extra.get('forxdays', 365)))):
418 class UserProperty(BaseModel):
419 user = models.ForeignKey(User, related_name='properties')
420 key = models.CharField(max_length=16)
421 value = PickledObjectField()
425 unique_together = ('user', 'key')
428 return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
431 def infer_cache_key(cls, querydict):
432 if 'user' in querydict and 'key' in querydict:
433 return cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
437 class UserPropertyDict(object):
438 def __init__(self, user):
439 self.__dict__['_user'] = user
441 def __get_property(self, name):
442 if self.__dict__.get('__%s__' % name, None):
443 return self.__dict__['__%s__' % name]
445 user = self.__dict__['_user']
446 prop = UserProperty.objects.get(user=user, key=name)
447 self.__dict__['__%s__' % name] = prop
448 self.__dict__[name] = prop.value
454 def __getattr__(self, name):
455 if self.__dict__.get(name, None):
456 return self.__dict__[name]
458 prop = self.__get_property(name)
465 def __setattr__(self, name, value):
466 current = self.__get_property(name)
468 if value is not None:
470 current.value = value
471 self.__dict__[name] = value
472 current.save(full_save=True)
474 user = self.__dict__['_user']
475 prop = UserProperty(user=user, value=value, key=name)
477 self.__dict__[name] = value
478 self.__dict__['__%s__' % name] = prop
482 del self.__dict__[name]
483 del self.__dict__['__%s__' % name]
486 class SubscriptionSettings(models.Model):
487 user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
489 enable_notifications = models.BooleanField(default=True)
492 member_joins = models.CharField(max_length=1, default='n')
493 new_question = models.CharField(max_length=1, default='n')
494 new_question_watched_tags = models.CharField(max_length=1, default='i')
495 subscribed_questions = models.CharField(max_length=1, default='i')
498 all_questions = models.BooleanField(default=False)
499 all_questions_watched_tags = models.BooleanField(default=False)
500 questions_viewed = models.BooleanField(default=False)
502 #notify activity on subscribed
503 notify_answers = models.BooleanField(default=True)
504 notify_reply_to_comments = models.BooleanField(default=True)
505 notify_comments_own_post = models.BooleanField(default=True)
506 notify_comments = models.BooleanField(default=False)
507 notify_accepted = models.BooleanField(default=False)
509 send_digest = models.BooleanField(default=True)
514 from forum.utils.time import one_day_from_now
516 class ValidationHashManager(models.Manager):
517 def _generate_md5_hash(self, user, type, hash_data, seed):
518 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
520 def create_new(self, user, type, hash_data=[], expiration=None):
521 seed = ''.join(Random().sample(string.letters+string.digits, 12))
522 hash = self._generate_md5_hash(user, type, hash_data, seed)
524 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
526 if expiration is not None:
527 obj.expiration = expiration
536 def validate(self, hash, user, type, hash_data=[]):
538 obj = self.get(hash_code=hash)
548 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
551 if obj.expiration < datetime.datetime.now():
560 class ValidationHash(models.Model):
561 hash_code = models.CharField(max_length=255, unique=True)
562 seed = models.CharField(max_length=12)
563 expiration = models.DateTimeField(default=one_day_from_now)
564 type = models.CharField(max_length=12)
565 user = models.ForeignKey(User)
567 objects = ValidationHashManager()
570 unique_together = ('user', 'type')
574 return self.hash_code
576 class AuthKeyUserAssociation(models.Model):
577 key = models.CharField(max_length=255, null=False, unique=True)
578 provider = models.CharField(max_length=64)
579 user = models.ForeignKey(User, related_name="auth_keys")
580 added_at = models.DateTimeField(default=datetime.datetime.now)