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 true_if_is_super_or_staff(fn):
89 def decorated(self, *args, **kwargs):
90 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
94 def false_if_validation_required_to(item):
96 def decorated(self, *args, **kwargs):
97 if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
100 return fn(self, *args, **kwargs)
104 class User(BaseModel, DjangoUser):
105 is_approved = models.BooleanField(default=False)
106 email_isvalid = models.BooleanField(default=False)
108 reputation = models.PositiveIntegerField(default=0)
109 gold = models.PositiveIntegerField(default=0)
110 silver = models.PositiveIntegerField(default=0)
111 bronze = models.PositiveIntegerField(default=0)
113 last_seen = models.DateTimeField(default=datetime.datetime.now)
114 real_name = models.CharField(max_length=100, blank=True)
115 website = models.URLField(max_length=200, blank=True)
116 location = models.CharField(max_length=100, blank=True)
117 date_of_birth = models.DateField(null=True, blank=True)
118 about = models.TextField(blank=True)
120 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
122 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
123 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
125 def __unicode__(self):
130 prop = self.__dict__.get('_prop', None)
133 prop = UserPropertyDict(self)
139 def is_siteowner(self):
140 #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
144 def decorated_name(self):
145 if settings.SHOW_STATUS_DIAMONDS:
146 if self.is_superuser:
147 return u"%s \u2666\u2666" % self.username
150 return u"%s \u2666" % self.username
155 def last_activity(self):
156 return self.actions.order_by('-action_date')[0].action_date
160 return md5(self.email).hexdigest()
162 def save(self, *args, **kwargs):
163 if self.reputation < 0:
166 new = not bool(self.id)
168 super(User, self).save(*args, **kwargs)
171 sub_settings = SubscriptionSettings(user=self)
174 def get_absolute_url(self):
175 return self.get_profile_url()
177 def get_messages(self):
179 for m in self.message_set.all():
180 messages.append(m.message)
183 def delete_messages(self):
184 self.message_set.all().delete()
187 def get_profile_url(self):
188 return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
190 def get_absolute_url(self):
191 return self.get_profile_url()
194 def get_asked_url(self):
195 return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(self.username)})
198 def get_answered_url(self):
199 return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
202 def get_subscribed_url(self):
203 return ('user_questions', (), {'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(self.username)})
205 def get_profile_link(self):
206 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
207 return mark_safe(profile_link)
209 def get_visible_answers(self, question):
210 return question.answers.filter_state(deleted=False)
212 def get_vote_count_today(self):
213 today = datetime.date.today()
214 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
215 action_date__gte=(today - datetime.timedelta(days=1))).count()
217 def get_reputation_by_upvoted_today(self):
218 today = datetime.datetime.now()
219 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
221 #todo: redo this, maybe transform in the daily cap
222 #if sum.get('value__sum', None) is not None: return sum['value__sum']
225 def get_flagged_items_count_today(self):
226 today = datetime.date.today()
227 return self.actions.filter(canceled=False, action_type="flag",
228 action_date__gte=(today - datetime.timedelta(days=1))).count()
230 @true_if_is_super_or_staff
231 def can_view_deleted_post(self, post):
232 return post.author == self
234 @true_if_is_super_or_staff
235 def can_vote_up(self):
236 return self.reputation >= int(settings.REP_TO_VOTE_UP)
238 @true_if_is_super_or_staff
239 def can_vote_down(self):
240 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
242 @false_if_validation_required_to('flag')
243 def can_flag_offensive(self, post=None):
244 if post is not None and post.author == self:
246 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
248 @true_if_is_super_or_staff
249 def can_view_offensive_flags(self, post=None):
250 if post is not None and post.author == self:
252 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
254 @true_if_is_super_or_staff
255 @false_if_validation_required_to('comment')
256 def can_comment(self, post):
257 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
258 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
260 @true_if_is_super_or_staff
261 def can_like_comment(self, comment):
262 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
264 @true_if_is_super_or_staff
265 def can_edit_comment(self, comment):
266 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
267 ) or self.is_superuser
269 @true_if_is_super_or_staff
270 def can_delete_comment(self, comment):
271 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
273 def can_convert_to_comment(self, answer):
274 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
275 (settings.REP_TO_CONVERT_TO_COMMENT))
277 @true_if_is_super_or_staff
278 def can_accept_answer(self, answer):
279 return self == answer.question.author
281 @true_if_is_super_or_staff
282 def can_create_tags(self):
283 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
285 @true_if_is_super_or_staff
286 def can_edit_post(self, post):
287 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
288 ) or (post.nis.wiki and self.reputation >= int(
289 settings.REP_TO_EDIT_WIKI))
291 @true_if_is_super_or_staff
292 def can_wikify(self, post):
293 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
295 @true_if_is_super_or_staff
296 def can_cancel_wiki(self, post):
297 return self == post.author
299 @true_if_is_super_or_staff
300 def can_retag_questions(self):
301 return self.reputation >= int(settings.REP_TO_RETAG)
303 @true_if_is_super_or_staff
304 def can_close_question(self, question):
305 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
306 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
308 @true_if_is_super_or_staff
309 def can_reopen_question(self, question):
310 return self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN
312 @true_if_is_super_or_staff
313 def can_delete_post(self, post):
314 if post.node_type == "comment":
315 return self.can_delete_comment(post)
317 return (self == post.author and (post.__class__.__name__ == "Answer" or
318 not post.answers.exclude(author=self).count()))
320 @true_if_is_super_or_staff
321 def can_upload_files(self):
322 return self.reputation >= int(settings.REP_TO_UPLOAD)
324 def email_valid_and_can_ask(self):
325 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
327 def email_valid_and_can_answer(self):
328 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
330 def check_password(self, old_passwd):
331 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
332 return DjangoUser.check_password(self, old_passwd)
335 def suspension(self):
336 if self.__dict__.get('_suspension_dencache_', False) != None:
338 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
339 except ObjectDoesNotExist:
340 self.__dict__['_suspension_dencache_'] = None
341 except MultipleObjectsReturned:
342 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
343 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
344 ).order_by('-action__action_date')[0]
346 return self.__dict__['_suspension_dencache_']
348 def _pop_suspension_cache(self):
349 self.__dict__.pop('_suspension_dencache_', None)
351 def is_suspended(self):
352 if not self.is_active:
353 suspension = self.suspension
355 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
356 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
357 days=int(suspension.extra.get('forxdays', 365)))):
367 class UserProperty(BaseModel):
368 user = models.ForeignKey(User, related_name='properties')
369 key = models.CharField(max_length=16)
370 value = PickledObjectField()
374 unique_together = ('user', 'key')
377 return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
380 def infer_cache_key(cls, querydict):
381 if 'user' in querydict and 'key' in querydict:
382 return cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
386 class UserPropertyDict(object):
387 def __init__(self, user):
388 self.__dict__['_user'] = user
390 def __get_property(self, name):
391 if self.__dict__.get('__%s__' % name, None):
392 return self.__dict__['__%s__' % name]
394 user = self.__dict__['_user']
395 prop = UserProperty.objects.get(user=user, key=name)
396 self.__dict__['__%s__' % name] = prop
397 self.__dict__[name] = prop.value
403 def __getattr__(self, name):
404 if self.__dict__.get(name, None):
405 return self.__dict__[name]
407 prop = self.__get_property(name)
414 def __setattr__(self, name, value):
415 current = self.__get_property(name)
417 if value is not None:
419 current.value = value
420 self.__dict__[name] = value
421 current.save(full_save=True)
423 user = self.__dict__['_user']
424 prop = UserProperty(user=user, value=value, key=name)
426 self.__dict__[name] = value
427 self.__dict__['__%s__' % name] = prop
431 del self.__dict__[name]
432 del self.__dict__['__%s__' % name]
435 class SubscriptionSettings(models.Model):
436 user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
438 enable_notifications = models.BooleanField(default=True)
441 member_joins = models.CharField(max_length=1, default='n')
442 new_question = models.CharField(max_length=1, default='n')
443 new_question_watched_tags = models.CharField(max_length=1, default='i')
444 subscribed_questions = models.CharField(max_length=1, default='i')
447 all_questions = models.BooleanField(default=False)
448 all_questions_watched_tags = models.BooleanField(default=False)
449 questions_asked = models.BooleanField(default=True)
450 questions_answered = models.BooleanField(default=True)
451 questions_commented = models.BooleanField(default=False)
452 questions_viewed = models.BooleanField(default=False)
454 #notify activity on subscribed
455 notify_answers = models.BooleanField(default=True)
456 notify_reply_to_comments = models.BooleanField(default=True)
457 notify_comments_own_post = models.BooleanField(default=True)
458 notify_comments = models.BooleanField(default=False)
459 notify_accepted = models.BooleanField(default=False)
461 send_digest = models.BooleanField(default=True)
466 from forum.utils.time import one_day_from_now
468 class ValidationHashManager(models.Manager):
469 def _generate_md5_hash(self, user, type, hash_data, seed):
470 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
472 def create_new(self, user, type, hash_data=[], expiration=None):
473 seed = ''.join(Random().sample(string.letters+string.digits, 12))
474 hash = self._generate_md5_hash(user, type, hash_data, seed)
476 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
478 if expiration is not None:
479 obj.expiration = expiration
488 def validate(self, hash, user, type, hash_data=[]):
490 obj = self.get(hash_code=hash)
500 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
503 if obj.expiration < datetime.datetime.now():
512 class ValidationHash(models.Model):
513 hash_code = models.CharField(max_length=255, unique=True)
514 seed = models.CharField(max_length=12)
515 expiration = models.DateTimeField(default=one_day_from_now)
516 type = models.CharField(max_length=12)
517 user = models.ForeignKey(User)
519 objects = ValidationHashManager()
522 unique_together = ('user', 'type')
526 return self.hash_code
528 class AuthKeyUserAssociation(models.Model):
529 key = models.CharField(max_length=255, null=False, unique=True)
530 provider = models.CharField(max_length=64)
531 user = models.ForeignKey(User, related_name="auth_keys")
532 added_at = models.DateTimeField(default=datetime.datetime.now)