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, Manager
8 from django.core.urlresolvers import get_script_prefix
10 from django.utils.encoding import smart_unicode
12 from forum.settings import TRUNCATE_LONG_USERNAMES, TRUNCATE_USERNAMES_LONGER_THAN
15 from random import Random
17 from django.utils.translation import ugettext as _
20 class AnonymousUser(DjangoAnonymousUser):
23 def get_visible_answers(self, question):
24 return question.answers.filter_state(deleted=False)
26 def can_view_deleted_post(self, post):
29 def can_vote_up(self):
32 def can_vote_down(self):
35 def can_vote_count_today(self):
38 def can_flag_offensive(self, post=None):
41 def can_view_offensive_flags(self, post=None):
44 def can_comment(self, post):
47 def can_like_comment(self, comment):
50 def can_edit_comment(self, comment):
53 def can_delete_comment(self, comment):
56 def can_convert_to_comment(self, answer):
59 def can_convert_to_question(self, answer):
62 def can_convert_comment_to_answer(self, comment):
65 def can_accept_answer(self, answer):
68 def can_create_tags(self):
71 def can_edit_post(self, post):
74 def can_wikify(self, post):
77 def can_cancel_wiki(self, post):
80 def can_retag_questions(self):
83 def can_close_question(self, question):
86 def can_reopen_question(self, question):
89 def can_delete_post(self, post):
92 def can_upload_files(self):
95 def is_a_super_user_or_staff(self):
98 def true_if_is_super_or_staff(fn):
99 def decorated(self, *args, **kwargs):
100 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
104 def false_if_validation_required_to(item):
106 def decorated(self, *args, **kwargs):
107 if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
110 return fn(self, *args, **kwargs)
114 class UserManager(CachedManager):
115 def get(self, *args, **kwargs):
116 if not len(args) and len(kwargs) == 1 and 'username' in kwargs:
117 matching_users = self.filter(username=kwargs['username'])
119 if len(matching_users) == 1:
120 return matching_users[0]
121 elif len(matching_users) > 1:
122 for user in matching_users:
123 if user.username == kwargs['username']:
125 return matching_users[0]
126 return super(UserManager, self).get(*args, **kwargs)
128 class User(BaseModel, DjangoUser):
129 is_approved = models.BooleanField(default=False)
130 email_isvalid = models.BooleanField(default=False)
132 reputation = models.IntegerField(default=0)
133 gold = models.PositiveIntegerField(default=0)
134 silver = models.PositiveIntegerField(default=0)
135 bronze = models.PositiveIntegerField(default=0)
137 last_seen = models.DateTimeField(default=datetime.datetime.now)
138 real_name = models.CharField(max_length=100, blank=True)
139 website = models.URLField(max_length=200, blank=True)
140 location = models.CharField(max_length=100, blank=True)
141 date_of_birth = models.DateField(null=True, blank=True)
142 about = models.TextField(blank=True)
144 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
146 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
147 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
149 objects = UserManager()
151 def __unicode__(self):
152 return smart_unicode(self.username)
156 prop = self.__dict__.get('_prop', None)
159 prop = UserPropertyDict(self)
165 def is_siteowner(self):
166 #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
170 def _decorated_name(self):
171 username = smart_unicode(self.username)
173 if len(username) > TRUNCATE_USERNAMES_LONGER_THAN and TRUNCATE_LONG_USERNAMES:
174 username = '%s...' % username[:TRUNCATE_USERNAMES_LONGER_THAN-3]
176 if settings.SHOW_STATUS_DIAMONDS:
177 if self.is_superuser:
178 return u"%s \u2666\u2666" % username
181 return u"%s \u2666" % username
186 def decorated_name(self):
187 return self._decorated_name()
190 def last_activity(self):
192 return self.actions.order_by('-action_date')[0].action_date
194 return self.last_seen
198 return md5(self.email.lower()).hexdigest()
200 def save(self, *args, **kwargs):
201 # If the community doesn't allow negative reputation, set it to 0
202 if not settings.ALLOW_NEGATIVE_REPUTATION and self.reputation < 0:
205 new = not bool(self.id)
207 super(User, self).save(*args, **kwargs)
210 sub_settings = SubscriptionSettings(user=self)
214 def get_profile_url(self):
215 keyword_arguments = {
216 'slug': slugify(smart_unicode(self.username))
218 if settings.INCLUDE_ID_IN_USER_URLS:
219 keyword_arguments.update({
222 return ('user_profile', (), keyword_arguments)
224 def get_absolute_url(self):
225 root_relative_url = self.get_profile_url()
226 relative_url = root_relative_url[len(get_script_prefix()):]
227 return '%s/%s' % (django_settings.APP_URL, relative_url)
230 def get_asked_url(self):
231 return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
234 def get_user_subscriptions_url(self):
235 keyword_arguments = {
236 'slug': slugify(smart_unicode(self.username))
238 if settings.INCLUDE_ID_IN_USER_URLS:
239 keyword_arguments.update({
242 return ('user_subscriptions', (), keyword_arguments)
245 def get_answered_url(self):
246 return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
248 def get_subscribed_url(self):
250 # Try to retrieve the Subscribed User URL.
251 url = reverse('user_questions',
252 kwargs={'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
255 # If some Exception has been raised, don't forget to log it.
256 logging.error("Error retrieving a subscribed user URL: %s" % e)
258 def get_profile_link(self):
259 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
260 return mark_safe(profile_link)
262 def get_visible_answers(self, question):
263 return question.answers.filter_state(deleted=False)
265 def get_vote_count_today(self):
266 today = datetime.date.today()
267 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
268 action_date__gte=(today - datetime.timedelta(days=1))).count()
270 def get_reputation_by_upvoted_today(self):
271 today = datetime.datetime.now()
272 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
274 #todo: redo this, maybe transform in the daily cap
275 #if sum.get('value__sum', None) is not None: return sum['value__sum']
278 def get_flagged_items_count_today(self):
279 today = datetime.date.today()
280 return self.actions.filter(canceled=False, action_type="flag",
281 action_date__gte=(today - datetime.timedelta(days=1))).count()
283 def can_vote_count_today(self):
284 votes_today = settings.MAX_VOTES_PER_DAY
286 if settings.USER_REPUTATION_TO_MAX_VOTES:
287 votes_today = votes_today + int(self.reputation)
291 def can_use_canned_comments(self):
292 # The canned comments feature is available only for admins and moderators,
293 # and only if the "Use canned comments" setting is activated in the administration.
294 if (self.is_superuser or self.is_staff) and settings.USE_CANNED_COMMENTS:
299 @true_if_is_super_or_staff
300 def can_view_deleted_post(self, post):
301 return post.author == self
303 @true_if_is_super_or_staff
304 def can_vote_up(self):
305 return self.reputation >= int(settings.REP_TO_VOTE_UP)
307 @true_if_is_super_or_staff
308 def can_vote_down(self):
309 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
311 @false_if_validation_required_to('flag')
312 def can_flag_offensive(self, post=None):
313 if post is not None and post.author == self:
315 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
317 @true_if_is_super_or_staff
318 def can_view_offensive_flags(self, post=None):
319 if post is not None and post.author == self:
321 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
323 @true_if_is_super_or_staff
324 @false_if_validation_required_to('comment')
325 def can_comment(self, post):
326 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
327 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
329 @true_if_is_super_or_staff
330 def can_like_comment(self, comment):
331 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
333 @true_if_is_super_or_staff
334 def can_edit_comment(self, comment):
335 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
336 ) or self.is_superuser
338 @true_if_is_super_or_staff
339 def can_delete_comment(self, comment):
340 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
342 def can_convert_comment_to_answer(self, comment):
343 # We need to know what is the comment parent node type.
344 comment_parent_type = comment.parent.node_type
346 # If the parent is not a question or an answer this comment cannot be converted to an answer.
347 if comment_parent_type != "question" and comment_parent_type != "answer":
350 return (comment.parent.node_type in ('question', 'answer')) and (self.is_superuser or self.is_staff or (
351 self == comment.author) or (self.reputation >= int(settings.REP_TO_CONVERT_COMMENTS_TO_ANSWERS)))
353 def can_convert_to_comment(self, answer):
354 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
355 (settings.REP_TO_CONVERT_TO_COMMENT))
357 def can_convert_to_question(self, node):
358 return (not node.marked) and (self.is_superuser or self.is_staff or node.author == self or self.reputation >= int
359 (settings.REP_TO_CONVERT_TO_QUESTION))
361 @true_if_is_super_or_staff
362 def can_accept_answer(self, answer):
363 return self == answer.question.author and (settings.USERS_CAN_ACCEPT_OWN or answer.author != answer.question.author)
365 @true_if_is_super_or_staff
366 def can_create_tags(self):
367 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
369 @true_if_is_super_or_staff
370 def can_edit_post(self, post):
371 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
372 ) or (post.nis.wiki and self.reputation >= int(
373 settings.REP_TO_EDIT_WIKI))
375 @true_if_is_super_or_staff
376 def can_wikify(self, post):
377 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
379 @true_if_is_super_or_staff
380 def can_cancel_wiki(self, post):
381 return self == post.author
383 @true_if_is_super_or_staff
384 def can_retag_questions(self):
385 return self.reputation >= int(settings.REP_TO_RETAG)
387 @true_if_is_super_or_staff
388 def can_close_question(self, question):
389 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
390 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
392 @true_if_is_super_or_staff
393 def can_reopen_question(self, question):
394 # Check whether the setting to Unify close and reopen permissions has been activated
395 if bool(settings.UNIFY_PERMISSIONS_TO_CLOSE_AND_REOPEN):
396 # If we unify close to reopen check whether the user has permissions to close.
397 # If he has -- he can reopen his question too.
399 self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
400 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
402 # Check whether the user is the author and has the required permissions to reopen
403 can_reopen = self == question.author and self.reputation >= int(settings.REP_TO_REOPEN_OWN)
406 @true_if_is_super_or_staff
407 def can_delete_post(self, post):
408 if post.node_type == "comment":
409 return self.can_delete_comment(post)
411 return (self == post.author and (post.__class__.__name__ == "Answer" or
412 not post.answers.exclude(author__id=self.id).count()))
414 @true_if_is_super_or_staff
415 def can_upload_files(self):
416 return self.reputation >= int(settings.REP_TO_UPLOAD)
418 @true_if_is_super_or_staff
419 def is_a_super_user_or_staff(self):
422 def email_valid_and_can_ask(self):
423 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
425 def email_valid_and_can_answer(self):
426 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
428 def check_password(self, old_passwd):
429 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
430 return DjangoUser.check_password(self, old_passwd)
433 def suspension(self):
434 if self.__dict__.get('_suspension_dencache_', False) != None:
436 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
437 except ObjectDoesNotExist:
438 self.__dict__['_suspension_dencache_'] = None
439 except MultipleObjectsReturned:
440 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
441 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
442 ).order_by('-action__action_date')[0].action
444 return self.__dict__['_suspension_dencache_']
446 def _pop_suspension_cache(self):
447 self.__dict__.pop('_suspension_dencache_', None)
449 def is_suspended(self):
450 if not self.is_active:
451 suspension = self.suspension
453 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
454 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
455 days=int(suspension.extra.get('forxdays', 365)))):
465 class UserProperty(BaseModel):
466 user = models.ForeignKey(User, related_name='properties')
467 key = models.CharField(max_length=16)
468 value = PickledObjectField()
472 unique_together = ('user', 'key')
475 return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
478 def infer_cache_key(cls, querydict):
479 if 'user' in querydict and 'key' in querydict:
480 cache_key = cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
481 if len(cache_key) > django_settings.CACHE_MAX_KEY_LENGTH:
482 cache_key = cache_key[:django_settings.CACHE_MAX_KEY_LENGTH]
487 class UserPropertyDict(object):
488 def __init__(self, user):
489 self.__dict__['_user'] = user
491 def __get_property(self, name):
492 if self.__dict__.get('__%s__' % name, None):
493 return self.__dict__['__%s__' % name]
495 user = self.__dict__['_user']
496 prop = UserProperty.objects.get(user=user, key=name)
497 self.__dict__['__%s__' % name] = prop
498 self.__dict__[name] = prop.value
504 def __getattr__(self, name):
505 if self.__dict__.get(name, None):
506 return self.__dict__[name]
508 prop = self.__get_property(name)
515 def __setattr__(self, name, value):
516 current = self.__get_property(name)
518 if value is not None:
520 current.value = value
521 self.__dict__[name] = value
522 current.save(full_save=True)
524 user = self.__dict__['_user']
525 prop = UserProperty(user=user, value=value, key=name)
527 self.__dict__[name] = value
528 self.__dict__['__%s__' % name] = prop
532 del self.__dict__[name]
533 del self.__dict__['__%s__' % name]
536 class SubscriptionSettings(models.Model):
537 user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
539 enable_notifications = models.BooleanField(default=True)
542 member_joins = models.CharField(max_length=1, default='n')
543 new_question = models.CharField(max_length=1, default='n')
544 new_question_watched_tags = models.CharField(max_length=1, default='i')
545 subscribed_questions = models.CharField(max_length=1, default='i')
548 all_questions = models.BooleanField(default=False)
549 all_questions_watched_tags = models.BooleanField(default=False)
550 questions_viewed = models.BooleanField(default=False)
552 #notify activity on subscribed
553 notify_answers = models.BooleanField(default=True)
554 notify_reply_to_comments = models.BooleanField(default=True)
555 notify_comments_own_post = models.BooleanField(default=True)
556 notify_comments = models.BooleanField(default=False)
557 notify_accepted = models.BooleanField(default=False)
559 send_digest = models.BooleanField(default=True)
564 from forum.utils.time import one_day_from_now
566 class ValidationHashManager(models.Manager):
567 def _generate_md5_hash(self, user, type, hash_data, seed):
568 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
570 def create_new(self, user, type, hash_data=[], expiration=None):
571 seed = ''.join(Random().sample(string.letters+string.digits, 12))
572 hash = self._generate_md5_hash(user, type, hash_data, seed)
574 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
576 if expiration is not None:
577 obj.expiration = expiration
586 def validate(self, hash, user, type, hash_data=[]):
588 obj = self.get(hash_code=hash)
598 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
601 if obj.expiration < datetime.datetime.now():
610 class ValidationHash(models.Model):
611 hash_code = models.CharField(max_length=255, unique=True)
612 seed = models.CharField(max_length=12)
613 expiration = models.DateTimeField(default=one_day_from_now)
614 type = models.CharField(max_length=12)
615 user = models.ForeignKey(User)
617 objects = ValidationHashManager()
620 unique_together = ('user', 'type')
624 return self.hash_code
626 class AuthKeyUserAssociation(models.Model):
627 key = models.CharField(max_length=255, null=False, unique=True)
628 provider = models.CharField(max_length=64)
629 user = models.ForeignKey(User, related_name="auth_keys")
630 added_at = models.DateTimeField(default=datetime.datetime.now)