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
9 from random import Random
11 from django.utils.translation import ugettext as _
14 class AnonymousUser(DjangoAnonymousUser):
17 def get_visible_answers(self, question):
18 return question.answers.filter_state(deleted=False)
20 def can_view_deleted_post(self, post):
23 def can_vote_up(self):
26 def can_vote_down(self):
29 def can_vote_count_today(self):
32 def can_flag_offensive(self, post=None):
35 def can_view_offensive_flags(self, post=None):
38 def can_comment(self, post):
41 def can_like_comment(self, comment):
44 def can_edit_comment(self, comment):
47 def can_delete_comment(self, comment):
50 def can_convert_to_comment(self, answer):
53 def can_convert_to_question(self, answer):
56 def can_convert_comment_to_answer(self, comment):
59 def can_accept_answer(self, answer):
62 def can_create_tags(self):
65 def can_edit_post(self, post):
68 def can_wikify(self, post):
71 def can_cancel_wiki(self, post):
74 def can_retag_questions(self):
77 def can_close_question(self, question):
80 def can_reopen_question(self, question):
83 def can_delete_post(self, post):
86 def can_upload_files(self):
89 def is_a_super_user_or_staff(self):
92 def true_if_is_super_or_staff(fn):
93 def decorated(self, *args, **kwargs):
94 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
98 def false_if_validation_required_to(item):
100 def decorated(self, *args, **kwargs):
101 if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
104 return fn(self, *args, **kwargs)
108 class User(BaseModel, DjangoUser):
109 is_approved = models.BooleanField(default=False)
110 email_isvalid = models.BooleanField(default=False)
112 reputation = models.PositiveIntegerField(default=0)
113 gold = models.PositiveIntegerField(default=0)
114 silver = models.PositiveIntegerField(default=0)
115 bronze = models.PositiveIntegerField(default=0)
117 last_seen = models.DateTimeField(default=datetime.datetime.now)
118 real_name = models.CharField(max_length=100, blank=True)
119 website = models.URLField(max_length=200, blank=True)
120 location = models.CharField(max_length=100, blank=True)
121 date_of_birth = models.DateField(null=True, blank=True)
122 about = models.TextField(blank=True)
124 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
126 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
127 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
129 def __unicode__(self):
134 prop = self.__dict__.get('_prop', None)
137 prop = UserPropertyDict(self)
143 def is_siteowner(self):
144 #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
148 def decorated_name(self):
149 if settings.SHOW_STATUS_DIAMONDS:
150 if self.is_superuser:
151 return u"%s \u2666\u2666" % self.username
154 return u"%s \u2666" % self.username
159 def last_activity(self):
161 return self.actions.order_by('-action_date')[0].action_date
163 return self.last_seen
167 return md5(self.email.lower()).hexdigest()
169 def save(self, *args, **kwargs):
170 if self.reputation < 0:
173 new = not bool(self.id)
175 super(User, self).save(*args, **kwargs)
178 sub_settings = SubscriptionSettings(user=self)
181 def get_messages(self):
183 for m in self.message_set.all():
184 messages.append(m.message)
187 def delete_messages(self):
188 self.message_set.all().delete()
191 def get_profile_url(self):
192 return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
194 def get_absolute_url(self):
195 return self.get_profile_url()
198 def get_asked_url(self):
199 return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(self.username)})
202 def get_answered_url(self):
203 return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
206 def get_subscribed_url(self):
207 return ('user_questions', (), {'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(self.username)})
209 def get_profile_link(self):
210 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
211 return mark_safe(profile_link)
213 def get_visible_answers(self, question):
214 return question.answers.filter_state(deleted=False)
216 def get_vote_count_today(self):
217 today = datetime.date.today()
218 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
219 action_date__gte=(today - datetime.timedelta(days=1))).count()
221 def get_reputation_by_upvoted_today(self):
222 today = datetime.datetime.now()
223 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
225 #todo: redo this, maybe transform in the daily cap
226 #if sum.get('value__sum', None) is not None: return sum['value__sum']
229 def get_flagged_items_count_today(self):
230 today = datetime.date.today()
231 return self.actions.filter(canceled=False, action_type="flag",
232 action_date__gte=(today - datetime.timedelta(days=1))).count()
234 def can_vote_count_today(self):
235 votes_today = settings.MAX_VOTES_PER_DAY
237 if settings.USER_REPUTATION_TO_MAX_VOTES:
238 votes_today = votes_today + int(self.reputation)
242 @true_if_is_super_or_staff
243 def can_view_deleted_post(self, post):
244 return post.author == self
246 @true_if_is_super_or_staff
247 def can_vote_up(self):
248 return self.reputation >= int(settings.REP_TO_VOTE_UP)
250 @true_if_is_super_or_staff
251 def can_vote_down(self):
252 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
254 @false_if_validation_required_to('flag')
255 def can_flag_offensive(self, post=None):
256 if post is not None and post.author == self:
258 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
260 @true_if_is_super_or_staff
261 def can_view_offensive_flags(self, post=None):
262 if post is not None and post.author == self:
264 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
266 @true_if_is_super_or_staff
267 @false_if_validation_required_to('comment')
268 def can_comment(self, post):
269 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
270 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
272 @true_if_is_super_or_staff
273 def can_like_comment(self, comment):
274 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
276 @true_if_is_super_or_staff
277 def can_edit_comment(self, comment):
278 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
279 ) or self.is_superuser
281 @true_if_is_super_or_staff
282 def can_delete_comment(self, comment):
283 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
285 @true_if_is_super_or_staff
286 def can_convert_comment_to_answer(self, comment):
287 return self == comment.author or self.reputation >= int(settings.REP_TO_CONVERT_COMMENTS_TO_ANSWERS)
289 def can_convert_to_comment(self, answer):
290 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
291 (settings.REP_TO_CONVERT_TO_COMMENT))
293 def can_convert_to_question(self, answer):
294 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
295 (settings.REP_TO_CONVERT_TO_QUESTION))
297 @true_if_is_super_or_staff
298 def can_accept_answer(self, answer):
299 return self == answer.question.author and (settings.USERS_CAN_ACCEPT_OWN or answer.author != answer.question.author)
301 @true_if_is_super_or_staff
302 def can_create_tags(self):
303 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
305 @true_if_is_super_or_staff
306 def can_edit_post(self, post):
307 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
308 ) or (post.nis.wiki and self.reputation >= int(
309 settings.REP_TO_EDIT_WIKI))
311 @true_if_is_super_or_staff
312 def can_wikify(self, post):
313 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
315 @true_if_is_super_or_staff
316 def can_cancel_wiki(self, post):
317 return self == post.author
319 @true_if_is_super_or_staff
320 def can_retag_questions(self):
321 return self.reputation >= int(settings.REP_TO_RETAG)
323 @true_if_is_super_or_staff
324 def can_close_question(self, question):
325 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
326 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
328 @true_if_is_super_or_staff
329 def can_reopen_question(self, question):
330 return self == question.author and self.reputation >= int(settings.REP_TO_REOPEN_OWN)
332 @true_if_is_super_or_staff
333 def can_delete_post(self, post):
334 if post.node_type == "comment":
335 return self.can_delete_comment(post)
337 return (self == post.author and (post.__class__.__name__ == "Answer" or
338 not post.answers.exclude(author__id=self.id).count()))
340 @true_if_is_super_or_staff
341 def can_upload_files(self):
342 return self.reputation >= int(settings.REP_TO_UPLOAD)
344 @true_if_is_super_or_staff
345 def is_a_super_user_or_staff(self):
348 def email_valid_and_can_ask(self):
349 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
351 def email_valid_and_can_answer(self):
352 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
354 def check_password(self, old_passwd):
355 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
356 return DjangoUser.check_password(self, old_passwd)
359 def suspension(self):
360 if self.__dict__.get('_suspension_dencache_', False) != None:
362 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
363 except ObjectDoesNotExist:
364 self.__dict__['_suspension_dencache_'] = None
365 except MultipleObjectsReturned:
366 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
367 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
368 ).order_by('-action__action_date')[0]
370 return self.__dict__['_suspension_dencache_']
372 def _pop_suspension_cache(self):
373 self.__dict__.pop('_suspension_dencache_', None)
375 def is_suspended(self):
376 if not self.is_active:
377 suspension = self.suspension
379 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
380 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
381 days=int(suspension.extra.get('forxdays', 365)))):
391 class UserProperty(BaseModel):
392 user = models.ForeignKey(User, related_name='properties')
393 key = models.CharField(max_length=16)
394 value = PickledObjectField()
398 unique_together = ('user', 'key')
401 return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
404 def infer_cache_key(cls, querydict):
405 if 'user' in querydict and 'key' in querydict:
406 return cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
410 class UserPropertyDict(object):
411 def __init__(self, user):
412 self.__dict__['_user'] = user
414 def __get_property(self, name):
415 if self.__dict__.get('__%s__' % name, None):
416 return self.__dict__['__%s__' % name]
418 user = self.__dict__['_user']
419 prop = UserProperty.objects.get(user=user, key=name)
420 self.__dict__['__%s__' % name] = prop
421 self.__dict__[name] = prop.value
427 def __getattr__(self, name):
428 if self.__dict__.get(name, None):
429 return self.__dict__[name]
431 prop = self.__get_property(name)
438 def __setattr__(self, name, value):
439 current = self.__get_property(name)
441 if value is not None:
443 current.value = value
444 self.__dict__[name] = value
445 current.save(full_save=True)
447 user = self.__dict__['_user']
448 prop = UserProperty(user=user, value=value, key=name)
450 self.__dict__[name] = value
451 self.__dict__['__%s__' % name] = prop
455 del self.__dict__[name]
456 del self.__dict__['__%s__' % name]
459 class SubscriptionSettings(models.Model):
460 user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
462 enable_notifications = models.BooleanField(default=True)
465 member_joins = models.CharField(max_length=1, default='n')
466 new_question = models.CharField(max_length=1, default='n')
467 new_question_watched_tags = models.CharField(max_length=1, default='i')
468 subscribed_questions = models.CharField(max_length=1, default='i')
471 all_questions = models.BooleanField(default=False)
472 all_questions_watched_tags = models.BooleanField(default=False)
473 questions_viewed = models.BooleanField(default=False)
475 #notify activity on subscribed
476 notify_answers = models.BooleanField(default=True)
477 notify_reply_to_comments = models.BooleanField(default=True)
478 notify_comments_own_post = models.BooleanField(default=True)
479 notify_comments = models.BooleanField(default=False)
480 notify_accepted = models.BooleanField(default=False)
482 send_digest = models.BooleanField(default=True)
487 from forum.utils.time import one_day_from_now
489 class ValidationHashManager(models.Manager):
490 def _generate_md5_hash(self, user, type, hash_data, seed):
491 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
493 def create_new(self, user, type, hash_data=[], expiration=None):
494 seed = ''.join(Random().sample(string.letters+string.digits, 12))
495 hash = self._generate_md5_hash(user, type, hash_data, seed)
497 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
499 if expiration is not None:
500 obj.expiration = expiration
509 def validate(self, hash, user, type, hash_data=[]):
511 obj = self.get(hash_code=hash)
521 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
524 if obj.expiration < datetime.datetime.now():
533 class ValidationHash(models.Model):
534 hash_code = models.CharField(max_length=255, unique=True)
535 seed = models.CharField(max_length=12)
536 expiration = models.DateTimeField(default=one_day_from_now)
537 type = models.CharField(max_length=12)
538 user = models.ForeignKey(User)
540 objects = ValidationHashManager()
543 unique_together = ('user', 'type')
547 return self.hash_code
549 class AuthKeyUserAssociation(models.Model):
550 key = models.CharField(max_length=255, null=False, unique=True)
551 provider = models.CharField(max_length=64)
552 user = models.ForeignKey(User, related_name="auth_keys")
553 added_at = models.DateTimeField(default=datetime.datetime.now)