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 hashlib import md5
10 from md5 import new as md5
13 from random import Random
15 from django.utils.translation import ugettext as _
18 QUESTIONS_PER_PAGE_CHOICES = (
24 class AnonymousUser(DjangoAnonymousUser):
25 def get_visible_answers(self, question):
26 return question.answers.filter_state(deleted=False)
28 def can_view_deleted_post(self, post):
31 def can_vote_up(self):
34 def can_vote_down(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_accept_answer(self, answer):
61 def can_create_tags(self):
64 def can_edit_post(self, post):
67 def can_wikify(self, post):
70 def can_cancel_wiki(self, post):
73 def can_retag_questions(self):
76 def can_close_question(self, question):
79 def can_reopen_question(self, question):
82 def can_delete_post(self, post):
85 def can_upload_files(self):
88 def is_a_super_user_or_staff(self):
91 def true_if_is_super_or_staff(fn):
92 def decorated(self, *args, **kwargs):
93 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
97 def false_if_validation_required_to(item):
99 def decorated(self, *args, **kwargs):
100 if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
103 return fn(self, *args, **kwargs)
107 class User(BaseModel, DjangoUser):
108 is_approved = models.BooleanField(default=False)
109 email_isvalid = models.BooleanField(default=False)
111 reputation = models.PositiveIntegerField(default=0)
112 gold = models.PositiveIntegerField(default=0)
113 silver = models.PositiveIntegerField(default=0)
114 bronze = models.PositiveIntegerField(default=0)
116 last_seen = models.DateTimeField(default=datetime.datetime.now)
117 real_name = models.CharField(max_length=100, blank=True)
118 website = models.URLField(max_length=200, blank=True)
119 location = models.CharField(max_length=100, blank=True)
120 date_of_birth = models.DateField(null=True, blank=True)
121 about = models.TextField(blank=True)
123 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
125 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
126 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
128 def __unicode__(self):
133 prop = self.__dict__.get('_prop', None)
136 prop = UserPropertyDict(self)
142 def is_siteowner(self):
143 #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
147 def decorated_name(self):
148 if settings.SHOW_STATUS_DIAMONDS:
149 if self.is_superuser:
150 return u"%s \u2666\u2666" % self.username
153 return u"%s \u2666" % self.username
158 def last_activity(self):
160 return self.actions.order_by('-action_date')[0].action_date
162 return self.last_seen
166 return md5(self.email.lower()).hexdigest()
168 def save(self, *args, **kwargs):
169 if self.reputation < 0:
172 new = not bool(self.id)
174 super(User, self).save(*args, **kwargs)
177 sub_settings = SubscriptionSettings(user=self)
180 def get_absolute_url(self):
181 return self.get_profile_url()
183 def get_messages(self):
185 for m in self.message_set.all():
186 messages.append(m.message)
189 def delete_messages(self):
190 self.message_set.all().delete()
193 def get_profile_url(self):
194 return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
196 def get_absolute_url(self):
197 return self.get_profile_url()
200 def get_asked_url(self):
201 return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(self.username)})
204 def get_answered_url(self):
205 return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
208 def get_subscribed_url(self):
209 return ('user_questions', (), {'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(self.username)})
211 def get_profile_link(self):
212 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
213 return mark_safe(profile_link)
215 def get_visible_answers(self, question):
216 return question.answers.filter_state(deleted=False)
218 def get_vote_count_today(self):
219 today = datetime.date.today()
220 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
221 action_date__gte=(today - datetime.timedelta(days=1))).count()
223 def get_reputation_by_upvoted_today(self):
224 today = datetime.datetime.now()
225 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
227 #todo: redo this, maybe transform in the daily cap
228 #if sum.get('value__sum', None) is not None: return sum['value__sum']
231 def get_flagged_items_count_today(self):
232 today = datetime.date.today()
233 return self.actions.filter(canceled=False, action_type="flag",
234 action_date__gte=(today - datetime.timedelta(days=1))).count()
236 @true_if_is_super_or_staff
237 def can_view_deleted_post(self, post):
238 return post.author == self
240 @true_if_is_super_or_staff
241 def can_vote_up(self):
242 return self.reputation >= int(settings.REP_TO_VOTE_UP)
244 @true_if_is_super_or_staff
245 def can_vote_down(self):
246 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
248 @false_if_validation_required_to('flag')
249 def can_flag_offensive(self, post=None):
250 if post is not None and post.author == self:
252 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
254 @true_if_is_super_or_staff
255 def can_view_offensive_flags(self, post=None):
256 if post is not None and post.author == self:
258 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
260 @true_if_is_super_or_staff
261 @false_if_validation_required_to('comment')
262 def can_comment(self, post):
263 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
264 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
266 @true_if_is_super_or_staff
267 def can_like_comment(self, comment):
268 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
270 @true_if_is_super_or_staff
271 def can_edit_comment(self, comment):
272 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
273 ) or self.is_superuser
275 @true_if_is_super_or_staff
276 def can_delete_comment(self, comment):
277 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
279 def can_convert_to_comment(self, answer):
280 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
281 (settings.REP_TO_CONVERT_TO_COMMENT))
283 def can_convert_to_question(self, answer):
284 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
285 (settings.REP_TO_CONVERT_TO_QUESTION))
287 @true_if_is_super_or_staff
288 def can_accept_answer(self, answer):
289 return self == answer.question.author and (settings.USERS_CAN_ACCEPT_OWN or answer.author != answer.question.author)
291 @true_if_is_super_or_staff
292 def can_create_tags(self):
293 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
295 @true_if_is_super_or_staff
296 def can_edit_post(self, post):
297 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
298 ) or (post.nis.wiki and self.reputation >= int(
299 settings.REP_TO_EDIT_WIKI))
301 @true_if_is_super_or_staff
302 def can_wikify(self, post):
303 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
305 @true_if_is_super_or_staff
306 def can_cancel_wiki(self, post):
307 return self == post.author
309 @true_if_is_super_or_staff
310 def can_retag_questions(self):
311 return self.reputation >= int(settings.REP_TO_RETAG)
313 @true_if_is_super_or_staff
314 def can_close_question(self, question):
315 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
316 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
318 @true_if_is_super_or_staff
319 def can_reopen_question(self, question):
320 return self == question.author and self.reputation >= int(settings.REP_TO_REOPEN_OWN)
322 @true_if_is_super_or_staff
323 def can_delete_post(self, post):
324 if post.node_type == "comment":
325 return self.can_delete_comment(post)
327 return (self == post.author and (post.__class__.__name__ == "Answer" or
328 not post.answers.exclude(author__id=self.id).count()))
330 @true_if_is_super_or_staff
331 def can_upload_files(self):
332 return self.reputation >= int(settings.REP_TO_UPLOAD)
334 @true_if_is_super_or_staff
335 def is_a_super_user_or_staff(self):
338 def email_valid_and_can_ask(self):
339 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
341 def email_valid_and_can_answer(self):
342 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
344 def check_password(self, old_passwd):
345 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
346 return DjangoUser.check_password(self, old_passwd)
349 def suspension(self):
350 if self.__dict__.get('_suspension_dencache_', False) != None:
352 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
353 except ObjectDoesNotExist:
354 self.__dict__['_suspension_dencache_'] = None
355 except MultipleObjectsReturned:
356 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
357 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
358 ).order_by('-action__action_date')[0]
360 return self.__dict__['_suspension_dencache_']
362 def _pop_suspension_cache(self):
363 self.__dict__.pop('_suspension_dencache_', None)
365 def is_suspended(self):
366 if not self.is_active:
367 suspension = self.suspension
369 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
370 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
371 days=int(suspension.extra.get('forxdays', 365)))):
381 class UserProperty(BaseModel):
382 user = models.ForeignKey(User, related_name='properties')
383 key = models.CharField(max_length=16)
384 value = PickledObjectField()
388 unique_together = ('user', 'key')
391 return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
394 def infer_cache_key(cls, querydict):
395 if 'user' in querydict and 'key' in querydict:
396 return cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
400 class UserPropertyDict(object):
401 def __init__(self, user):
402 self.__dict__['_user'] = user
404 def __get_property(self, name):
405 if self.__dict__.get('__%s__' % name, None):
406 return self.__dict__['__%s__' % name]
408 user = self.__dict__['_user']
409 prop = UserProperty.objects.get(user=user, key=name)
410 self.__dict__['__%s__' % name] = prop
411 self.__dict__[name] = prop.value
417 def __getattr__(self, name):
418 if self.__dict__.get(name, None):
419 return self.__dict__[name]
421 prop = self.__get_property(name)
428 def __setattr__(self, name, value):
429 current = self.__get_property(name)
431 if value is not None:
433 current.value = value
434 self.__dict__[name] = value
435 current.save(full_save=True)
437 user = self.__dict__['_user']
438 prop = UserProperty(user=user, value=value, key=name)
440 self.__dict__[name] = value
441 self.__dict__['__%s__' % name] = prop
445 del self.__dict__[name]
446 del self.__dict__['__%s__' % name]
449 class SubscriptionSettings(models.Model):
450 user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
452 enable_notifications = models.BooleanField(default=True)
455 member_joins = models.CharField(max_length=1, default='n')
456 new_question = models.CharField(max_length=1, default='n')
457 new_question_watched_tags = models.CharField(max_length=1, default='i')
458 subscribed_questions = models.CharField(max_length=1, default='i')
461 all_questions = models.BooleanField(default=False)
462 all_questions_watched_tags = models.BooleanField(default=False)
463 questions_asked = models.BooleanField(default=True)
464 questions_answered = models.BooleanField(default=True)
465 questions_commented = models.BooleanField(default=False)
466 questions_viewed = models.BooleanField(default=False)
468 #notify activity on subscribed
469 notify_answers = models.BooleanField(default=True)
470 notify_reply_to_comments = models.BooleanField(default=True)
471 notify_comments_own_post = models.BooleanField(default=True)
472 notify_comments = models.BooleanField(default=False)
473 notify_accepted = models.BooleanField(default=False)
475 send_digest = models.BooleanField(default=True)
480 from forum.utils.time import one_day_from_now
482 class ValidationHashManager(models.Manager):
483 def _generate_md5_hash(self, user, type, hash_data, seed):
484 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
486 def create_new(self, user, type, hash_data=[], expiration=None):
487 seed = ''.join(Random().sample(string.letters+string.digits, 12))
488 hash = self._generate_md5_hash(user, type, hash_data, seed)
490 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
492 if expiration is not None:
493 obj.expiration = expiration
502 def validate(self, hash, user, type, hash_data=[]):
504 obj = self.get(hash_code=hash)
514 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
517 if obj.expiration < datetime.datetime.now():
526 class ValidationHash(models.Model):
527 hash_code = models.CharField(max_length=255, unique=True)
528 seed = models.CharField(max_length=12)
529 expiration = models.DateTimeField(default=one_day_from_now)
530 type = models.CharField(max_length=12)
531 user = models.ForeignKey(User)
533 objects = ValidationHashManager()
536 unique_together = ('user', 'type')
540 return self.hash_code
542 class AuthKeyUserAssociation(models.Model):
543 key = models.CharField(max_length=255, null=False, unique=True)
544 provider = models.CharField(max_length=64)
545 user = models.ForeignKey(User, related_name="auth_keys")
546 added_at = models.DateTimeField(default=datetime.datetime.now)