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 django.utils.encoding import smart_unicode
10 from forum.settings import TRUNCATE_LONG_USERNAMES, TRUNCATE_USERNAMES_LONGER_THAN
13 from random import Random
15 from django.utils.translation import ugettext as _
18 class AnonymousUser(DjangoAnonymousUser):
21 def get_visible_answers(self, question):
22 return question.answers.filter_state(deleted=False)
24 def can_view_deleted_post(self, post):
27 def can_vote_up(self):
30 def can_vote_down(self):
33 def can_vote_count_today(self):
36 def can_flag_offensive(self, post=None):
39 def can_view_offensive_flags(self, post=None):
42 def can_comment(self, post):
45 def can_like_comment(self, comment):
48 def can_edit_comment(self, comment):
51 def can_delete_comment(self, comment):
54 def can_convert_to_comment(self, answer):
57 def can_convert_to_question(self, answer):
60 def can_convert_comment_to_answer(self, comment):
63 def can_accept_answer(self, answer):
66 def can_create_tags(self):
69 def can_edit_post(self, post):
72 def can_wikify(self, post):
75 def can_cancel_wiki(self, post):
78 def can_retag_questions(self):
81 def can_close_question(self, question):
84 def can_reopen_question(self, question):
87 def can_delete_post(self, post):
90 def can_upload_files(self):
93 def is_a_super_user_or_staff(self):
96 def true_if_is_super_or_staff(fn):
97 def decorated(self, *args, **kwargs):
98 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
102 def false_if_validation_required_to(item):
104 def decorated(self, *args, **kwargs):
105 if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
108 return fn(self, *args, **kwargs)
112 class User(BaseModel, DjangoUser):
113 is_approved = models.BooleanField(default=False)
114 email_isvalid = models.BooleanField(default=False)
116 reputation = models.PositiveIntegerField(default=0)
117 gold = models.PositiveIntegerField(default=0)
118 silver = models.PositiveIntegerField(default=0)
119 bronze = models.PositiveIntegerField(default=0)
121 last_seen = models.DateTimeField(default=datetime.datetime.now)
122 real_name = models.CharField(max_length=100, blank=True)
123 website = models.URLField(max_length=200, blank=True)
124 location = models.CharField(max_length=100, blank=True)
125 date_of_birth = models.DateField(null=True, blank=True)
126 about = models.TextField(blank=True)
128 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
130 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
131 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
133 def __unicode__(self):
134 return smart_unicode(self.username)
138 prop = self.__dict__.get('_prop', None)
141 prop = UserPropertyDict(self)
147 def is_siteowner(self):
148 #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
152 def decorated_name(self):
153 username = smart_unicode(self.username)
155 if len(username) > TRUNCATE_USERNAMES_LONGER_THAN and TRUNCATE_LONG_USERNAMES:
156 username = '%s...' % username[:TRUNCATE_USERNAMES_LONGER_THAN-3]
158 if settings.SHOW_STATUS_DIAMONDS:
159 if self.is_superuser:
160 return u"%s \u2666\u2666" % username
163 return u"%s \u2666" % username
168 def last_activity(self):
170 return self.actions.order_by('-action_date')[0].action_date
172 return self.last_seen
176 return md5(self.email.lower()).hexdigest()
178 def save(self, *args, **kwargs):
179 if self.reputation < 0:
182 new = not bool(self.id)
184 super(User, self).save(*args, **kwargs)
187 sub_settings = SubscriptionSettings(user=self)
190 def get_messages(self):
192 for m in self.message_set.all():
193 messages.append(m.message)
196 def delete_messages(self):
197 self.message_set.all().delete()
200 def get_profile_url(self):
201 return ('user_profile', (), {'id': self.id, 'slug': slugify(smart_unicode(self.username))})
203 def get_absolute_url(self):
204 return self.get_profile_url()
207 def get_asked_url(self):
208 return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(self.username)})
211 def get_answered_url(self):
212 return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
214 def get_subscribed_url(self):
216 # Try to retrieve the Subscribed User URL.
217 url = reverse('user_questions',
218 kwargs={'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
221 # If some Exception has been raised, don't forget to log it.
222 logging.error("Error retrieving a subscribed user URL: %s" % e)
224 def get_profile_link(self):
225 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
226 return mark_safe(profile_link)
228 def get_visible_answers(self, question):
229 return question.answers.filter_state(deleted=False)
231 def get_vote_count_today(self):
232 today = datetime.date.today()
233 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
234 action_date__gte=(today - datetime.timedelta(days=1))).count()
236 def get_reputation_by_upvoted_today(self):
237 today = datetime.datetime.now()
238 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
240 #todo: redo this, maybe transform in the daily cap
241 #if sum.get('value__sum', None) is not None: return sum['value__sum']
244 def get_flagged_items_count_today(self):
245 today = datetime.date.today()
246 return self.actions.filter(canceled=False, action_type="flag",
247 action_date__gte=(today - datetime.timedelta(days=1))).count()
249 def can_vote_count_today(self):
250 votes_today = settings.MAX_VOTES_PER_DAY
252 if settings.USER_REPUTATION_TO_MAX_VOTES:
253 votes_today = votes_today + int(self.reputation)
257 @true_if_is_super_or_staff
258 def can_view_deleted_post(self, post):
259 return post.author == self
261 @true_if_is_super_or_staff
262 def can_vote_up(self):
263 return self.reputation >= int(settings.REP_TO_VOTE_UP)
265 @true_if_is_super_or_staff
266 def can_vote_down(self):
267 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
269 @false_if_validation_required_to('flag')
270 def can_flag_offensive(self, post=None):
271 if post is not None and post.author == self:
273 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
275 @true_if_is_super_or_staff
276 def can_view_offensive_flags(self, post=None):
277 if post is not None and post.author == self:
279 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
281 @true_if_is_super_or_staff
282 @false_if_validation_required_to('comment')
283 def can_comment(self, post):
284 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
285 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
287 @true_if_is_super_or_staff
288 def can_like_comment(self, comment):
289 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
291 @true_if_is_super_or_staff
292 def can_edit_comment(self, comment):
293 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
294 ) or self.is_superuser
296 @true_if_is_super_or_staff
297 def can_delete_comment(self, comment):
298 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
300 def can_convert_comment_to_answer(self, comment):
301 # We need to know what is the comment parent node type.
302 comment_parent_type = comment.parent.node_type
304 # If the parent is not a question or an answer this comment cannot be converted to an answer.
305 if comment_parent_type != "question" and comment_parent_type != "answer":
308 return (comment.parent.node_type in ('question', 'answer')) and (self.is_superuser or self.is_staff or (
309 self == comment.author) or (self.reputation >= int(settings.REP_TO_CONVERT_COMMENTS_TO_ANSWERS)))
311 def can_convert_to_comment(self, answer):
312 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
313 (settings.REP_TO_CONVERT_TO_COMMENT))
315 def can_convert_to_question(self, answer):
316 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
317 (settings.REP_TO_CONVERT_TO_QUESTION))
319 @true_if_is_super_or_staff
320 def can_accept_answer(self, answer):
321 return self == answer.question.author and (settings.USERS_CAN_ACCEPT_OWN or answer.author != answer.question.author)
323 @true_if_is_super_or_staff
324 def can_create_tags(self):
325 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
327 @true_if_is_super_or_staff
328 def can_edit_post(self, post):
329 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
330 ) or (post.nis.wiki and self.reputation >= int(
331 settings.REP_TO_EDIT_WIKI))
333 @true_if_is_super_or_staff
334 def can_wikify(self, post):
335 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
337 @true_if_is_super_or_staff
338 def can_cancel_wiki(self, post):
339 return self == post.author
341 @true_if_is_super_or_staff
342 def can_retag_questions(self):
343 return self.reputation >= int(settings.REP_TO_RETAG)
345 @true_if_is_super_or_staff
346 def can_close_question(self, question):
347 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
348 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
350 @true_if_is_super_or_staff
351 def can_reopen_question(self, question):
352 return self == question.author and self.reputation >= int(settings.REP_TO_REOPEN_OWN)
354 @true_if_is_super_or_staff
355 def can_delete_post(self, post):
356 if post.node_type == "comment":
357 return self.can_delete_comment(post)
359 return (self == post.author and (post.__class__.__name__ == "Answer" or
360 not post.answers.exclude(author__id=self.id).count()))
362 @true_if_is_super_or_staff
363 def can_upload_files(self):
364 return self.reputation >= int(settings.REP_TO_UPLOAD)
366 @true_if_is_super_or_staff
367 def is_a_super_user_or_staff(self):
370 def email_valid_and_can_ask(self):
371 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
373 def email_valid_and_can_answer(self):
374 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
376 def check_password(self, old_passwd):
377 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
378 return DjangoUser.check_password(self, old_passwd)
381 def suspension(self):
382 if self.__dict__.get('_suspension_dencache_', False) != None:
384 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
385 except ObjectDoesNotExist:
386 self.__dict__['_suspension_dencache_'] = None
387 except MultipleObjectsReturned:
388 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
389 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
390 ).order_by('-action__action_date')[0]
392 return self.__dict__['_suspension_dencache_']
394 def _pop_suspension_cache(self):
395 self.__dict__.pop('_suspension_dencache_', None)
397 def is_suspended(self):
398 if not self.is_active:
399 suspension = self.suspension
401 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
402 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
403 days=int(suspension.extra.get('forxdays', 365)))):
413 class UserProperty(BaseModel):
414 user = models.ForeignKey(User, related_name='properties')
415 key = models.CharField(max_length=16)
416 value = PickledObjectField()
420 unique_together = ('user', 'key')
423 return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
426 def infer_cache_key(cls, querydict):
427 if 'user' in querydict and 'key' in querydict:
428 return cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
432 class UserPropertyDict(object):
433 def __init__(self, user):
434 self.__dict__['_user'] = user
436 def __get_property(self, name):
437 if self.__dict__.get('__%s__' % name, None):
438 return self.__dict__['__%s__' % name]
440 user = self.__dict__['_user']
441 prop = UserProperty.objects.get(user=user, key=name)
442 self.__dict__['__%s__' % name] = prop
443 self.__dict__[name] = prop.value
449 def __getattr__(self, name):
450 if self.__dict__.get(name, None):
451 return self.__dict__[name]
453 prop = self.__get_property(name)
460 def __setattr__(self, name, value):
461 current = self.__get_property(name)
463 if value is not None:
465 current.value = value
466 self.__dict__[name] = value
467 current.save(full_save=True)
469 user = self.__dict__['_user']
470 prop = UserProperty(user=user, value=value, key=name)
472 self.__dict__[name] = value
473 self.__dict__['__%s__' % name] = prop
477 del self.__dict__[name]
478 del self.__dict__['__%s__' % name]
481 class SubscriptionSettings(models.Model):
482 user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
484 enable_notifications = models.BooleanField(default=True)
487 member_joins = models.CharField(max_length=1, default='n')
488 new_question = models.CharField(max_length=1, default='n')
489 new_question_watched_tags = models.CharField(max_length=1, default='i')
490 subscribed_questions = models.CharField(max_length=1, default='i')
493 all_questions = models.BooleanField(default=False)
494 all_questions_watched_tags = models.BooleanField(default=False)
495 questions_viewed = models.BooleanField(default=False)
497 #notify activity on subscribed
498 notify_answers = models.BooleanField(default=True)
499 notify_reply_to_comments = models.BooleanField(default=True)
500 notify_comments_own_post = models.BooleanField(default=True)
501 notify_comments = models.BooleanField(default=False)
502 notify_accepted = models.BooleanField(default=False)
504 send_digest = models.BooleanField(default=True)
509 from forum.utils.time import one_day_from_now
511 class ValidationHashManager(models.Manager):
512 def _generate_md5_hash(self, user, type, hash_data, seed):
513 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
515 def create_new(self, user, type, hash_data=[], expiration=None):
516 seed = ''.join(Random().sample(string.letters+string.digits, 12))
517 hash = self._generate_md5_hash(user, type, hash_data, seed)
519 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
521 if expiration is not None:
522 obj.expiration = expiration
531 def validate(self, hash, user, type, hash_data=[]):
533 obj = self.get(hash_code=hash)
543 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
546 if obj.expiration < datetime.datetime.now():
555 class ValidationHash(models.Model):
556 hash_code = models.CharField(max_length=255, unique=True)
557 seed = models.CharField(max_length=12)
558 expiration = models.DateTimeField(default=one_day_from_now)
559 type = models.CharField(max_length=12)
560 user = models.ForeignKey(User)
562 objects = ValidationHashManager()
565 unique_together = ('user', 'type')
569 return self.hash_code
571 class AuthKeyUserAssociation(models.Model):
572 key = models.CharField(max_length=255, null=False, unique=True)
573 provider = models.CharField(max_length=64)
574 user = models.ForeignKey(User, related_name="auth_keys")
575 added_at = models.DateTimeField(default=datetime.datetime.now)