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_convert_to_question(self, answer):
61 def can_convert_comment_to_answer(self, comment):
64 def can_accept_answer(self, answer):
67 def can_create_tags(self):
70 def can_edit_post(self, post):
73 def can_wikify(self, post):
76 def can_cancel_wiki(self, post):
79 def can_retag_questions(self):
82 def can_close_question(self, question):
85 def can_reopen_question(self, question):
88 def can_delete_post(self, post):
91 def can_upload_files(self):
94 def is_a_super_user_or_staff(self):
97 def true_if_is_super_or_staff(fn):
98 def decorated(self, *args, **kwargs):
99 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
103 def false_if_validation_required_to(item):
105 def decorated(self, *args, **kwargs):
106 if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
109 return fn(self, *args, **kwargs)
113 class User(BaseModel, DjangoUser):
114 is_approved = models.BooleanField(default=False)
115 email_isvalid = models.BooleanField(default=False)
117 reputation = models.PositiveIntegerField(default=0)
118 gold = models.PositiveIntegerField(default=0)
119 silver = models.PositiveIntegerField(default=0)
120 bronze = models.PositiveIntegerField(default=0)
122 last_seen = models.DateTimeField(default=datetime.datetime.now)
123 real_name = models.CharField(max_length=100, blank=True)
124 website = models.URLField(max_length=200, blank=True)
125 location = models.CharField(max_length=100, blank=True)
126 date_of_birth = models.DateField(null=True, blank=True)
127 about = models.TextField(blank=True)
129 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
131 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
132 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
134 def __unicode__(self):
139 prop = self.__dict__.get('_prop', None)
142 prop = UserPropertyDict(self)
148 def is_siteowner(self):
149 #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
153 def decorated_name(self):
154 if settings.SHOW_STATUS_DIAMONDS:
155 if self.is_superuser:
156 return u"%s \u2666\u2666" % self.username
159 return u"%s \u2666" % self.username
164 def last_activity(self):
166 return self.actions.order_by('-action_date')[0].action_date
168 return self.last_seen
172 return md5(self.email.lower()).hexdigest()
174 def save(self, *args, **kwargs):
175 if self.reputation < 0:
178 new = not bool(self.id)
180 super(User, self).save(*args, **kwargs)
183 sub_settings = SubscriptionSettings(user=self)
186 def get_absolute_url(self):
187 return self.get_profile_url()
189 def get_messages(self):
191 for m in self.message_set.all():
192 messages.append(m.message)
195 def delete_messages(self):
196 self.message_set.all().delete()
199 def get_profile_url(self):
200 return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
202 def get_absolute_url(self):
203 return self.get_profile_url()
206 def get_asked_url(self):
207 return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(self.username)})
210 def get_answered_url(self):
211 return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
214 def get_subscribed_url(self):
215 return ('user_questions', (), {'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(self.username)})
217 def get_profile_link(self):
218 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
219 return mark_safe(profile_link)
221 def get_visible_answers(self, question):
222 return question.answers.filter_state(deleted=False)
224 def get_vote_count_today(self):
225 today = datetime.date.today()
226 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
227 action_date__gte=(today - datetime.timedelta(days=1))).count()
229 def get_reputation_by_upvoted_today(self):
230 today = datetime.datetime.now()
231 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
233 #todo: redo this, maybe transform in the daily cap
234 #if sum.get('value__sum', None) is not None: return sum['value__sum']
237 def get_flagged_items_count_today(self):
238 today = datetime.date.today()
239 return self.actions.filter(canceled=False, action_type="flag",
240 action_date__gte=(today - datetime.timedelta(days=1))).count()
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_asked = models.BooleanField(default=True)
474 questions_answered = models.BooleanField(default=True)
475 questions_commented = models.BooleanField(default=False)
476 questions_viewed = models.BooleanField(default=False)
478 #notify activity on subscribed
479 notify_answers = models.BooleanField(default=True)
480 notify_reply_to_comments = models.BooleanField(default=True)
481 notify_comments_own_post = models.BooleanField(default=True)
482 notify_comments = models.BooleanField(default=False)
483 notify_accepted = models.BooleanField(default=False)
485 send_digest = models.BooleanField(default=True)
490 from forum.utils.time import one_day_from_now
492 class ValidationHashManager(models.Manager):
493 def _generate_md5_hash(self, user, type, hash_data, seed):
494 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
496 def create_new(self, user, type, hash_data=[], expiration=None):
497 seed = ''.join(Random().sample(string.letters+string.digits, 12))
498 hash = self._generate_md5_hash(user, type, hash_data, seed)
500 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
502 if expiration is not None:
503 obj.expiration = expiration
512 def validate(self, hash, user, type, hash_data=[]):
514 obj = self.get(hash_code=hash)
524 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
527 if obj.expiration < datetime.datetime.now():
536 class ValidationHash(models.Model):
537 hash_code = models.CharField(max_length=255, unique=True)
538 seed = models.CharField(max_length=12)
539 expiration = models.DateTimeField(default=one_day_from_now)
540 type = models.CharField(max_length=12)
541 user = models.ForeignKey(User)
543 objects = ValidationHashManager()
546 unique_together = ('user', 'type')
550 return self.hash_code
552 class AuthKeyUserAssociation(models.Model):
553 key = models.CharField(max_length=255, null=False, unique=True)
554 provider = models.CharField(max_length=64)
555 user = models.ForeignKey(User, related_name="auth_keys")
556 added_at = models.DateTimeField(default=datetime.datetime.now)