2 from utils import PickledObjectField
3 from django.conf import settings as django_settings
4 from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
5 from django.contrib.contenttypes.models import ContentType
6 from django.contrib.auth.models import User as DjangoUser, AnonymousUser as DjangoAnonymousUser
7 from django.db.models import Q
9 from django.utils.encoding import smart_unicode
11 from forum.settings import TRUNCATE_LONG_USERNAMES, TRUNCATE_USERNAMES_LONGER_THAN
14 from random import Random
16 from django.utils.translation import ugettext as _
19 class AnonymousUser(DjangoAnonymousUser):
22 def get_visible_answers(self, question):
23 return question.answers.filter_state(deleted=False)
25 def can_view_deleted_post(self, post):
28 def can_vote_up(self):
31 def can_vote_down(self):
34 def can_vote_count_today(self):
37 def can_flag_offensive(self, post=None):
40 def can_view_offensive_flags(self, post=None):
43 def can_comment(self, post):
46 def can_like_comment(self, comment):
49 def can_edit_comment(self, comment):
52 def can_delete_comment(self, comment):
55 def can_convert_to_comment(self, answer):
58 def can_convert_to_question(self, answer):
61 def can_convert_comment_to_answer(self, comment):
64 def can_accept_answer(self, answer):
67 def can_create_tags(self):
70 def can_edit_post(self, post):
73 def can_wikify(self, post):
76 def can_cancel_wiki(self, post):
79 def can_retag_questions(self):
82 def can_close_question(self, question):
85 def can_reopen_question(self, question):
88 def can_delete_post(self, post):
91 def can_upload_files(self):
94 def is_a_super_user_or_staff(self):
97 def true_if_is_super_or_staff(fn):
98 def decorated(self, *args, **kwargs):
99 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
103 def false_if_validation_required_to(item):
105 def decorated(self, *args, **kwargs):
106 if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
109 return fn(self, *args, **kwargs)
113 class User(BaseModel, DjangoUser):
114 is_approved = models.BooleanField(default=False)
115 email_isvalid = models.BooleanField(default=False)
117 reputation = models.IntegerField(default=0)
118 gold = models.PositiveIntegerField(default=0)
119 silver = models.PositiveIntegerField(default=0)
120 bronze = models.PositiveIntegerField(default=0)
122 last_seen = models.DateTimeField(default=datetime.datetime.now)
123 real_name = models.CharField(max_length=100, blank=True)
124 website = models.URLField(max_length=200, blank=True)
125 location = models.CharField(max_length=100, blank=True)
126 date_of_birth = models.DateField(null=True, blank=True)
127 about = models.TextField(blank=True)
129 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
131 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
132 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
134 def __unicode__(self):
135 return smart_unicode(self.username)
139 prop = self.__dict__.get('_prop', None)
142 prop = UserPropertyDict(self)
148 def is_siteowner(self):
149 #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
153 def decorated_name(self):
154 username = smart_unicode(self.username)
156 if len(username) > TRUNCATE_USERNAMES_LONGER_THAN and TRUNCATE_LONG_USERNAMES:
157 username = '%s...' % username[:TRUNCATE_USERNAMES_LONGER_THAN-3]
159 if settings.SHOW_STATUS_DIAMONDS:
160 if self.is_superuser:
161 return u"%s \u2666\u2666" % username
164 return u"%s \u2666" % username
169 def last_activity(self):
171 return self.actions.order_by('-action_date')[0].action_date
173 return self.last_seen
177 return md5(self.email.lower()).hexdigest()
179 def save(self, *args, **kwargs):
180 # If the community doesn't allow negative reputation, set it to 0
181 if not settings.ALLOW_NEGATIVE_REPUTATION and self.reputation < 0:
184 new = not bool(self.id)
186 super(User, self).save(*args, **kwargs)
189 sub_settings = SubscriptionSettings(user=self)
192 def get_messages(self):
194 for m in self.message_set.all():
195 messages.append(m.message)
198 def delete_messages(self):
199 self.message_set.all().delete()
202 def get_profile_url(self):
203 keyword_arguments = {
204 'slug': slugify(smart_unicode(self.username))
206 if settings.INCLUDE_ID_IN_USER_URLS:
207 keyword_arguments.update({
210 return ('user_profile', (), keyword_arguments)
212 def get_absolute_url(self):
213 return self.get_profile_url()
216 def get_asked_url(self):
217 return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
220 def get_user_subscriptions_url(self):
221 keyword_arguments = {
222 'slug': slugify(smart_unicode(self.username))
224 if settings.INCLUDE_ID_IN_USER_URLS:
225 keyword_arguments.update({
228 return ('user_subscriptions', (), keyword_arguments)
231 def get_answered_url(self):
232 return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
234 def get_subscribed_url(self):
236 # Try to retrieve the Subscribed User URL.
237 url = reverse('user_questions',
238 kwargs={'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
241 # If some Exception has been raised, don't forget to log it.
242 logging.error("Error retrieving a subscribed user URL: %s" % e)
244 def get_profile_link(self):
245 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
246 return mark_safe(profile_link)
248 def get_visible_answers(self, question):
249 return question.answers.filter_state(deleted=False)
251 def get_vote_count_today(self):
252 today = datetime.date.today()
253 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
254 action_date__gte=(today - datetime.timedelta(days=1))).count()
256 def get_reputation_by_upvoted_today(self):
257 today = datetime.datetime.now()
258 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
260 #todo: redo this, maybe transform in the daily cap
261 #if sum.get('value__sum', None) is not None: return sum['value__sum']
264 def get_flagged_items_count_today(self):
265 today = datetime.date.today()
266 return self.actions.filter(canceled=False, action_type="flag",
267 action_date__gte=(today - datetime.timedelta(days=1))).count()
269 def can_vote_count_today(self):
270 votes_today = settings.MAX_VOTES_PER_DAY
272 if settings.USER_REPUTATION_TO_MAX_VOTES:
273 votes_today = votes_today + int(self.reputation)
277 def can_use_canned_comments(self):
278 # The canned comments feature is available only for admins and moderators,
279 # and only if the "Use canned comments" setting is activated in the administration.
280 if (self.is_superuser or self.is_staff) and settings.USE_CANNED_COMMENTS:
285 @true_if_is_super_or_staff
286 def can_view_deleted_post(self, post):
287 return post.author == self
289 @true_if_is_super_or_staff
290 def can_vote_up(self):
291 return self.reputation >= int(settings.REP_TO_VOTE_UP)
293 @true_if_is_super_or_staff
294 def can_vote_down(self):
295 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
297 @false_if_validation_required_to('flag')
298 def can_flag_offensive(self, post=None):
299 if post is not None and post.author == self:
301 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
303 @true_if_is_super_or_staff
304 def can_view_offensive_flags(self, post=None):
305 if post is not None and post.author == self:
307 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
309 @true_if_is_super_or_staff
310 @false_if_validation_required_to('comment')
311 def can_comment(self, post):
312 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
313 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
315 @true_if_is_super_or_staff
316 def can_like_comment(self, comment):
317 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
319 @true_if_is_super_or_staff
320 def can_edit_comment(self, comment):
321 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
322 ) or self.is_superuser
324 @true_if_is_super_or_staff
325 def can_delete_comment(self, comment):
326 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
328 def can_convert_comment_to_answer(self, comment):
329 # We need to know what is the comment parent node type.
330 comment_parent_type = comment.parent.node_type
332 # If the parent is not a question or an answer this comment cannot be converted to an answer.
333 if comment_parent_type != "question" and comment_parent_type != "answer":
336 return (comment.parent.node_type in ('question', 'answer')) and (self.is_superuser or self.is_staff or (
337 self == comment.author) or (self.reputation >= int(settings.REP_TO_CONVERT_COMMENTS_TO_ANSWERS)))
339 def can_convert_to_comment(self, answer):
340 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
341 (settings.REP_TO_CONVERT_TO_COMMENT))
343 def can_convert_to_question(self, node):
344 return (not node.marked) and (self.is_superuser or self.is_staff or node.author == self or self.reputation >= int
345 (settings.REP_TO_CONVERT_TO_QUESTION))
347 @true_if_is_super_or_staff
348 def can_accept_answer(self, answer):
349 return self == answer.question.author and (settings.USERS_CAN_ACCEPT_OWN or answer.author != answer.question.author)
351 @true_if_is_super_or_staff
352 def can_create_tags(self):
353 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
355 @true_if_is_super_or_staff
356 def can_edit_post(self, post):
357 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
358 ) or (post.nis.wiki and self.reputation >= int(
359 settings.REP_TO_EDIT_WIKI))
361 @true_if_is_super_or_staff
362 def can_wikify(self, post):
363 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
365 @true_if_is_super_or_staff
366 def can_cancel_wiki(self, post):
367 return self == post.author
369 @true_if_is_super_or_staff
370 def can_retag_questions(self):
371 return self.reputation >= int(settings.REP_TO_RETAG)
373 @true_if_is_super_or_staff
374 def can_close_question(self, question):
375 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
376 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
378 @true_if_is_super_or_staff
379 def can_reopen_question(self, question):
380 # Check whether the setting to Unify close and reopen permissions has been activated
381 if bool(settings.UNIFY_PERMISSIONS_TO_CLOSE_AND_REOPEN):
382 # If we unify close to reopen check whether the user has permissions to close.
383 # If he has -- he can reopen his question too.
385 self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
386 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
388 # Check whether the user is the author and has the required permissions to reopen
389 can_reopen = self == question.author and self.reputation >= int(settings.REP_TO_REOPEN_OWN)
392 @true_if_is_super_or_staff
393 def can_delete_post(self, post):
394 if post.node_type == "comment":
395 return self.can_delete_comment(post)
397 return (self == post.author and (post.__class__.__name__ == "Answer" or
398 not post.answers.exclude(author__id=self.id).count()))
400 @true_if_is_super_or_staff
401 def can_upload_files(self):
402 return self.reputation >= int(settings.REP_TO_UPLOAD)
404 @true_if_is_super_or_staff
405 def is_a_super_user_or_staff(self):
408 def email_valid_and_can_ask(self):
409 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
411 def email_valid_and_can_answer(self):
412 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
414 def check_password(self, old_passwd):
415 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
416 return DjangoUser.check_password(self, old_passwd)
419 def suspension(self):
420 if self.__dict__.get('_suspension_dencache_', False) != None:
422 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
423 except ObjectDoesNotExist:
424 self.__dict__['_suspension_dencache_'] = None
425 except MultipleObjectsReturned:
426 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
427 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
428 ).order_by('-action__action_date')[0].action
430 return self.__dict__['_suspension_dencache_']
432 def _pop_suspension_cache(self):
433 self.__dict__.pop('_suspension_dencache_', None)
435 def is_suspended(self):
436 if not self.is_active:
437 suspension = self.suspension
439 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
440 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
441 days=int(suspension.extra.get('forxdays', 365)))):
451 class UserProperty(BaseModel):
452 user = models.ForeignKey(User, related_name='properties')
453 key = models.CharField(max_length=16)
454 value = PickledObjectField()
458 unique_together = ('user', 'key')
461 return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
464 def infer_cache_key(cls, querydict):
465 if 'user' in querydict and 'key' in querydict:
466 cache_key = cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
467 if len(cache_key) > django_settings.CACHE_MAX_KEY_LENGTH:
468 cache_key = cache_key[:django_settings.CACHE_MAX_KEY_LENGTH]
473 class UserPropertyDict(object):
474 def __init__(self, user):
475 self.__dict__['_user'] = user
477 def __get_property(self, name):
478 if self.__dict__.get('__%s__' % name, None):
479 return self.__dict__['__%s__' % name]
481 user = self.__dict__['_user']
482 prop = UserProperty.objects.get(user=user, key=name)
483 self.__dict__['__%s__' % name] = prop
484 self.__dict__[name] = prop.value
490 def __getattr__(self, name):
491 if self.__dict__.get(name, None):
492 return self.__dict__[name]
494 prop = self.__get_property(name)
501 def __setattr__(self, name, value):
502 current = self.__get_property(name)
504 if value is not None:
506 current.value = value
507 self.__dict__[name] = value
508 current.save(full_save=True)
510 user = self.__dict__['_user']
511 prop = UserProperty(user=user, value=value, key=name)
513 self.__dict__[name] = value
514 self.__dict__['__%s__' % name] = prop
518 del self.__dict__[name]
519 del self.__dict__['__%s__' % name]
522 class SubscriptionSettings(models.Model):
523 user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
525 enable_notifications = models.BooleanField(default=True)
528 member_joins = models.CharField(max_length=1, default='n')
529 new_question = models.CharField(max_length=1, default='n')
530 new_question_watched_tags = models.CharField(max_length=1, default='i')
531 subscribed_questions = models.CharField(max_length=1, default='i')
534 all_questions = models.BooleanField(default=False)
535 all_questions_watched_tags = models.BooleanField(default=False)
536 questions_viewed = models.BooleanField(default=False)
538 #notify activity on subscribed
539 notify_answers = models.BooleanField(default=True)
540 notify_reply_to_comments = models.BooleanField(default=True)
541 notify_comments_own_post = models.BooleanField(default=True)
542 notify_comments = models.BooleanField(default=False)
543 notify_accepted = models.BooleanField(default=False)
545 send_digest = models.BooleanField(default=True)
550 from forum.utils.time import one_day_from_now
552 class ValidationHashManager(models.Manager):
553 def _generate_md5_hash(self, user, type, hash_data, seed):
554 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
556 def create_new(self, user, type, hash_data=[], expiration=None):
557 seed = ''.join(Random().sample(string.letters+string.digits, 12))
558 hash = self._generate_md5_hash(user, type, hash_data, seed)
560 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
562 if expiration is not None:
563 obj.expiration = expiration
572 def validate(self, hash, user, type, hash_data=[]):
574 obj = self.get(hash_code=hash)
584 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
587 if obj.expiration < datetime.datetime.now():
596 class ValidationHash(models.Model):
597 hash_code = models.CharField(max_length=255, unique=True)
598 seed = models.CharField(max_length=12)
599 expiration = models.DateTimeField(default=one_day_from_now)
600 type = models.CharField(max_length=12)
601 user = models.ForeignKey(User)
603 objects = ValidationHashManager()
606 unique_together = ('user', 'type')
610 return self.hash_code
612 class AuthKeyUserAssociation(models.Model):
613 key = models.CharField(max_length=255, null=False, unique=True)
614 provider = models.CharField(max_length=64)
615 user = models.ForeignKey(User, related_name="auth_keys")
616 added_at = models.DateTimeField(default=datetime.datetime.now)