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 forum.settings import TRUNCATE_LONG_USERNAMES, TRUNCATE_USERNAMES_LONGER_THAN
11 from random import Random
13 from django.utils.translation import ugettext as _
16 class AnonymousUser(DjangoAnonymousUser):
19 def get_visible_answers(self, question):
20 return question.answers.filter_state(deleted=False)
22 def can_view_deleted_post(self, post):
25 def can_vote_up(self):
28 def can_vote_down(self):
31 def can_vote_count_today(self):
34 def can_flag_offensive(self, post=None):
37 def can_view_offensive_flags(self, post=None):
40 def can_comment(self, post):
43 def can_like_comment(self, comment):
46 def can_edit_comment(self, comment):
49 def can_delete_comment(self, comment):
52 def can_convert_to_comment(self, answer):
55 def can_convert_to_question(self, answer):
58 def can_convert_comment_to_answer(self, comment):
61 def can_accept_answer(self, answer):
64 def can_create_tags(self):
67 def can_edit_post(self, post):
70 def can_wikify(self, post):
73 def can_cancel_wiki(self, post):
76 def can_retag_questions(self):
79 def can_close_question(self, question):
82 def can_reopen_question(self, question):
85 def can_delete_post(self, post):
88 def can_upload_files(self):
91 def is_a_super_user_or_staff(self):
94 def true_if_is_super_or_staff(fn):
95 def decorated(self, *args, **kwargs):
96 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
100 def false_if_validation_required_to(item):
102 def decorated(self, *args, **kwargs):
103 if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
106 return fn(self, *args, **kwargs)
110 class User(BaseModel, DjangoUser):
111 is_approved = models.BooleanField(default=False)
112 email_isvalid = models.BooleanField(default=False)
114 reputation = models.PositiveIntegerField(default=0)
115 gold = models.PositiveIntegerField(default=0)
116 silver = models.PositiveIntegerField(default=0)
117 bronze = models.PositiveIntegerField(default=0)
119 last_seen = models.DateTimeField(default=datetime.datetime.now)
120 real_name = models.CharField(max_length=100, blank=True)
121 website = models.URLField(max_length=200, blank=True)
122 location = models.CharField(max_length=100, blank=True)
123 date_of_birth = models.DateField(null=True, blank=True)
124 about = models.TextField(blank=True)
126 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
128 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
129 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
131 def __unicode__(self):
136 prop = self.__dict__.get('_prop', None)
139 prop = UserPropertyDict(self)
145 def is_siteowner(self):
146 #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
150 def decorated_name(self):
151 username = self.username
153 if len(username) > TRUNCATE_USERNAMES_LONGER_THAN and TRUNCATE_LONG_USERNAMES:
154 username = '%s...' % username[:TRUNCATE_USERNAMES_LONGER_THAN-3]
156 if settings.SHOW_STATUS_DIAMONDS:
157 if self.is_superuser:
158 return u"%s \u2666\u2666" % username
161 return u"%s \u2666" % username
166 def last_activity(self):
168 return self.actions.order_by('-action_date')[0].action_date
170 return self.last_seen
174 return md5(self.email.lower()).hexdigest()
176 def save(self, *args, **kwargs):
177 if self.reputation < 0:
180 new = not bool(self.id)
182 super(User, self).save(*args, **kwargs)
185 sub_settings = SubscriptionSettings(user=self)
188 def get_messages(self):
190 for m in self.message_set.all():
191 messages.append(m.message)
194 def delete_messages(self):
195 self.message_set.all().delete()
198 def get_profile_url(self):
199 return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
201 def get_absolute_url(self):
202 return self.get_profile_url()
205 def get_asked_url(self):
206 return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(self.username)})
209 def get_answered_url(self):
210 return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
213 def get_subscribed_url(self):
214 return ('user_questions', (), {'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(self.username)})
216 def get_profile_link(self):
217 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
218 return mark_safe(profile_link)
220 def get_visible_answers(self, question):
221 return question.answers.filter_state(deleted=False)
223 def get_vote_count_today(self):
224 today = datetime.date.today()
225 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
226 action_date__gte=(today - datetime.timedelta(days=1))).count()
228 def get_reputation_by_upvoted_today(self):
229 today = datetime.datetime.now()
230 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
232 #todo: redo this, maybe transform in the daily cap
233 #if sum.get('value__sum', None) is not None: return sum['value__sum']
236 def get_flagged_items_count_today(self):
237 today = datetime.date.today()
238 return self.actions.filter(canceled=False, action_type="flag",
239 action_date__gte=(today - datetime.timedelta(days=1))).count()
241 def can_vote_count_today(self):
242 votes_today = settings.MAX_VOTES_PER_DAY
244 if settings.USER_REPUTATION_TO_MAX_VOTES:
245 votes_today = votes_today + int(self.reputation)
249 @true_if_is_super_or_staff
250 def can_view_deleted_post(self, post):
251 return post.author == self
253 @true_if_is_super_or_staff
254 def can_vote_up(self):
255 return self.reputation >= int(settings.REP_TO_VOTE_UP)
257 @true_if_is_super_or_staff
258 def can_vote_down(self):
259 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
261 @false_if_validation_required_to('flag')
262 def can_flag_offensive(self, post=None):
263 if post is not None and post.author == self:
265 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
267 @true_if_is_super_or_staff
268 def can_view_offensive_flags(self, post=None):
269 if post is not None and post.author == self:
271 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
273 @true_if_is_super_or_staff
274 @false_if_validation_required_to('comment')
275 def can_comment(self, post):
276 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
277 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
279 @true_if_is_super_or_staff
280 def can_like_comment(self, comment):
281 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
283 @true_if_is_super_or_staff
284 def can_edit_comment(self, comment):
285 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
286 ) or self.is_superuser
288 @true_if_is_super_or_staff
289 def can_delete_comment(self, comment):
290 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
292 def can_convert_comment_to_answer(self, comment):
293 return (comment.parent.node_type in ('question', 'answer')) and (self.is_superuser or self.is_staff or (
294 self == comment.author) or (self.reputation >= int(settings.REP_TO_CONVERT_COMMENTS_TO_ANSWERS)))
296 def can_convert_to_comment(self, answer):
297 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
298 (settings.REP_TO_CONVERT_TO_COMMENT))
300 def can_convert_to_question(self, answer):
301 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
302 (settings.REP_TO_CONVERT_TO_QUESTION))
304 @true_if_is_super_or_staff
305 def can_accept_answer(self, answer):
306 return self == answer.question.author and (settings.USERS_CAN_ACCEPT_OWN or answer.author != answer.question.author)
308 @true_if_is_super_or_staff
309 def can_create_tags(self):
310 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
312 @true_if_is_super_or_staff
313 def can_edit_post(self, post):
314 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
315 ) or (post.nis.wiki and self.reputation >= int(
316 settings.REP_TO_EDIT_WIKI))
318 @true_if_is_super_or_staff
319 def can_wikify(self, post):
320 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
322 @true_if_is_super_or_staff
323 def can_cancel_wiki(self, post):
324 return self == post.author
326 @true_if_is_super_or_staff
327 def can_retag_questions(self):
328 return self.reputation >= int(settings.REP_TO_RETAG)
330 @true_if_is_super_or_staff
331 def can_close_question(self, question):
332 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
333 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
335 @true_if_is_super_or_staff
336 def can_reopen_question(self, question):
337 return self == question.author and self.reputation >= int(settings.REP_TO_REOPEN_OWN)
339 @true_if_is_super_or_staff
340 def can_delete_post(self, post):
341 if post.node_type == "comment":
342 return self.can_delete_comment(post)
344 return (self == post.author and (post.__class__.__name__ == "Answer" or
345 not post.answers.exclude(author__id=self.id).count()))
347 @true_if_is_super_or_staff
348 def can_upload_files(self):
349 return self.reputation >= int(settings.REP_TO_UPLOAD)
351 @true_if_is_super_or_staff
352 def is_a_super_user_or_staff(self):
355 def email_valid_and_can_ask(self):
356 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
358 def email_valid_and_can_answer(self):
359 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
361 def check_password(self, old_passwd):
362 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
363 return DjangoUser.check_password(self, old_passwd)
366 def suspension(self):
367 if self.__dict__.get('_suspension_dencache_', False) != None:
369 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
370 except ObjectDoesNotExist:
371 self.__dict__['_suspension_dencache_'] = None
372 except MultipleObjectsReturned:
373 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
374 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
375 ).order_by('-action__action_date')[0]
377 return self.__dict__['_suspension_dencache_']
379 def _pop_suspension_cache(self):
380 self.__dict__.pop('_suspension_dencache_', None)
382 def is_suspended(self):
383 if not self.is_active:
384 suspension = self.suspension
386 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
387 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
388 days=int(suspension.extra.get('forxdays', 365)))):
398 class UserProperty(BaseModel):
399 user = models.ForeignKey(User, related_name='properties')
400 key = models.CharField(max_length=16)
401 value = PickledObjectField()
405 unique_together = ('user', 'key')
408 return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
411 def infer_cache_key(cls, querydict):
412 if 'user' in querydict and 'key' in querydict:
413 return cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
417 class UserPropertyDict(object):
418 def __init__(self, user):
419 self.__dict__['_user'] = user
421 def __get_property(self, name):
422 if self.__dict__.get('__%s__' % name, None):
423 return self.__dict__['__%s__' % name]
425 user = self.__dict__['_user']
426 prop = UserProperty.objects.get(user=user, key=name)
427 self.__dict__['__%s__' % name] = prop
428 self.__dict__[name] = prop.value
434 def __getattr__(self, name):
435 if self.__dict__.get(name, None):
436 return self.__dict__[name]
438 prop = self.__get_property(name)
445 def __setattr__(self, name, value):
446 current = self.__get_property(name)
448 if value is not None:
450 current.value = value
451 self.__dict__[name] = value
452 current.save(full_save=True)
454 user = self.__dict__['_user']
455 prop = UserProperty(user=user, value=value, key=name)
457 self.__dict__[name] = value
458 self.__dict__['__%s__' % name] = prop
462 del self.__dict__[name]
463 del self.__dict__['__%s__' % name]
466 class SubscriptionSettings(models.Model):
467 user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
469 enable_notifications = models.BooleanField(default=True)
472 member_joins = models.CharField(max_length=1, default='n')
473 new_question = models.CharField(max_length=1, default='n')
474 new_question_watched_tags = models.CharField(max_length=1, default='i')
475 subscribed_questions = models.CharField(max_length=1, default='i')
478 all_questions = models.BooleanField(default=False)
479 all_questions_watched_tags = models.BooleanField(default=False)
480 questions_viewed = models.BooleanField(default=False)
482 #notify activity on subscribed
483 notify_answers = models.BooleanField(default=True)
484 notify_reply_to_comments = models.BooleanField(default=True)
485 notify_comments_own_post = models.BooleanField(default=True)
486 notify_comments = models.BooleanField(default=False)
487 notify_accepted = models.BooleanField(default=False)
489 send_digest = models.BooleanField(default=True)
494 from forum.utils.time import one_day_from_now
496 class ValidationHashManager(models.Manager):
497 def _generate_md5_hash(self, user, type, hash_data, seed):
498 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
500 def create_new(self, user, type, hash_data=[], expiration=None):
501 seed = ''.join(Random().sample(string.letters+string.digits, 12))
502 hash = self._generate_md5_hash(user, type, hash_data, seed)
504 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
506 if expiration is not None:
507 obj.expiration = expiration
516 def validate(self, hash, user, type, hash_data=[]):
518 obj = self.get(hash_code=hash)
528 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
531 if obj.expiration < datetime.datetime.now():
540 class ValidationHash(models.Model):
541 hash_code = models.CharField(max_length=255, unique=True)
542 seed = models.CharField(max_length=12)
543 expiration = models.DateTimeField(default=one_day_from_now)
544 type = models.CharField(max_length=12)
545 user = models.ForeignKey(User)
547 objects = ValidationHashManager()
550 unique_together = ('user', 'type')
554 return self.hash_code
556 class AuthKeyUserAssociation(models.Model):
557 key = models.CharField(max_length=255, null=False, unique=True)
558 provider = models.CharField(max_length=64)
559 user = models.ForeignKey(User, related_name="auth_keys")
560 added_at = models.DateTimeField(default=datetime.datetime.now)