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
156 return md5(self.email).hexdigest()
158 def save(self, *args, **kwargs):
159 if self.reputation < 0:
162 new = not bool(self.id)
164 super(User, self).save(*args, **kwargs)
167 sub_settings = SubscriptionSettings(user=self)
170 def get_absolute_url(self):
171 return self.get_profile_url()
173 def get_messages(self):
175 for m in self.message_set.all():
176 messages.append(m.message)
179 def delete_messages(self):
180 self.message_set.all().delete()
183 def get_profile_url(self):
184 return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
186 def get_absolute_url(self):
187 return self.get_profile_url()
190 def get_asked_url(self):
191 return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(self.username)})
194 def get_answered_url(self):
195 return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
198 def get_subscribed_url(self):
199 return ('user_questions', (), {'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(self.username)})
201 def get_profile_link(self):
202 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
203 return mark_safe(profile_link)
205 def get_visible_answers(self, question):
206 return question.answers.filter_state(deleted=False)
208 def get_vote_count_today(self):
209 today = datetime.date.today()
210 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
211 action_date__gte=(today - datetime.timedelta(days=1))).count()
213 def get_reputation_by_upvoted_today(self):
214 today = datetime.datetime.now()
215 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
217 #todo: redo this, maybe transform in the daily cap
218 #if sum.get('value__sum', None) is not None: return sum['value__sum']
221 def get_flagged_items_count_today(self):
222 today = datetime.date.today()
223 return self.actions.filter(canceled=False, action_type="flag",
224 action_date__gte=(today - datetime.timedelta(days=1))).count()
226 @true_if_is_super_or_staff
227 def can_view_deleted_post(self, post):
228 return post.author == self
230 @true_if_is_super_or_staff
231 def can_vote_up(self):
232 return self.reputation >= int(settings.REP_TO_VOTE_UP)
234 @true_if_is_super_or_staff
235 def can_vote_down(self):
236 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
238 @false_if_validation_required_to('flag')
239 def can_flag_offensive(self, post=None):
240 if post is not None and post.author == self:
242 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
244 @true_if_is_super_or_staff
245 def can_view_offensive_flags(self, post=None):
246 if post is not None and post.author == self:
248 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
250 @true_if_is_super_or_staff
251 @false_if_validation_required_to('comment')
252 def can_comment(self, post):
253 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
254 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
256 @true_if_is_super_or_staff
257 def can_like_comment(self, comment):
258 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
260 @true_if_is_super_or_staff
261 def can_edit_comment(self, comment):
262 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
263 ) or self.is_superuser
265 @true_if_is_super_or_staff
266 def can_delete_comment(self, comment):
267 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
269 def can_convert_to_comment(self, answer):
270 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
271 (settings.REP_TO_CONVERT_TO_COMMENT))
273 @true_if_is_super_or_staff
274 def can_accept_answer(self, answer):
275 return self == answer.question.author
277 @true_if_is_super_or_staff
278 def can_create_tags(self):
279 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
281 @true_if_is_super_or_staff
282 def can_edit_post(self, post):
283 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
284 ) or (post.nis.wiki and self.reputation >= int(
285 settings.REP_TO_EDIT_WIKI))
287 @true_if_is_super_or_staff
288 def can_wikify(self, post):
289 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
291 @true_if_is_super_or_staff
292 def can_cancel_wiki(self, post):
293 return self == post.author
295 @true_if_is_super_or_staff
296 def can_retag_questions(self):
297 return self.reputation >= int(settings.REP_TO_RETAG)
299 @true_if_is_super_or_staff
300 def can_close_question(self, question):
301 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
302 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
304 @true_if_is_super_or_staff
305 def can_reopen_question(self, question):
306 return self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN
308 @true_if_is_super_or_staff
309 def can_delete_post(self, post):
310 if post.node_type == "comment":
311 return self.can_delete_comment(post)
313 return (self == post.author and (post.__class__.__name__ == "Answer" or
314 not post.answers.exclude(author=self).count()))
316 @true_if_is_super_or_staff
317 def can_upload_files(self):
318 return self.reputation >= int(settings.REP_TO_UPLOAD)
320 def email_valid_and_can_ask(self):
321 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
323 def email_valid_and_can_answer(self):
324 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
326 def check_password(self, old_passwd):
327 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
328 return DjangoUser.check_password(self, old_passwd)
331 def suspension(self):
332 if self.__dict__.get('_suspension_dencache_', False) != None:
334 self.__dict__['_suspension_dencache_'] = self.actions.get(action_type="suspend", canceled=False)
335 except ObjectDoesNotExist:
336 self.__dict__['_suspension_dencache_'] = None
337 except MultipleObjectsReturned:
338 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
339 self.__dict__['_suspension_dencache_'] = self.actions.filter(action_type="suspend", canceled=False
340 ).order_by('-action_date')[0]
342 return self.__dict__['_suspension_dencache_']
344 def _pop_suspension_cache(self):
345 self.__dict__.pop('_suspension_dencache_', None)
347 def is_suspended(self):
348 if not self.is_active:
349 suspension = self.suspension
351 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
352 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
353 days=int(suspension.extra.get('forxdays', 365)))):
363 class UserProperty(models.Model):
364 user = models.ForeignKey(User, related_name='properties')
365 key = models.CharField(max_length=16)
366 value = PickledObjectField()
370 unique_together = ('user', 'key')
372 class UserPropertyDict(object):
373 def __init__(self, user):
374 self.__dict__['_user'] = user
376 def __get_property(self, name):
377 if self.__dict__.get('__%s__' % name, None):
378 return self.__dict__['__%s__' % name]
380 user = self.__dict__['_user']
381 prop = UserProperty.objects.get(user=user, key=name)
382 self.__dict__['__%s__' % name] = prop
383 self.__dict__[name] = prop.value
389 def __getattr__(self, name):
390 if self.__dict__.get(name, None):
391 return self.__dict__[name]
393 prop = self.__get_property(name)
400 def __setattr__(self, name, value):
401 current = self.__get_property(name)
403 if value is not None:
405 current.value = value
406 self.__dict__[name] = value
409 user = self.__dict__['_user']
410 prop = UserProperty(user=user, value=value, key=name)
412 self.__dict__[name] = value
413 self.__dict__['__%s__' % name] = prop
417 del self.__dict__[name]
418 del self.__dict__['__%s__' % name]
421 class SubscriptionSettings(models.Model):
422 user = models.OneToOneField(User, related_name='subscription_settings')
424 enable_notifications = models.BooleanField(default=True)
427 member_joins = models.CharField(max_length=1, default='n')
428 new_question = models.CharField(max_length=1, default='n')
429 new_question_watched_tags = models.CharField(max_length=1, default='i')
430 subscribed_questions = models.CharField(max_length=1, default='i')
433 all_questions = models.BooleanField(default=False)
434 all_questions_watched_tags = models.BooleanField(default=False)
435 questions_asked = models.BooleanField(default=True)
436 questions_answered = models.BooleanField(default=True)
437 questions_commented = models.BooleanField(default=False)
438 questions_viewed = models.BooleanField(default=False)
440 #notify activity on subscribed
441 notify_answers = models.BooleanField(default=True)
442 notify_reply_to_comments = models.BooleanField(default=True)
443 notify_comments_own_post = models.BooleanField(default=True)
444 notify_comments = models.BooleanField(default=False)
445 notify_accepted = models.BooleanField(default=False)
447 send_digest = models.BooleanField(default=True)
452 from forum.utils.time import one_day_from_now
454 class ValidationHashManager(models.Manager):
455 def _generate_md5_hash(self, user, type, hash_data, seed):
456 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
458 def create_new(self, user, type, hash_data=[], expiration=None):
459 seed = ''.join(Random().sample(string.letters+string.digits, 12))
460 hash = self._generate_md5_hash(user, type, hash_data, seed)
462 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
464 if expiration is not None:
465 obj.expiration = expiration
474 def validate(self, hash, user, type, hash_data=[]):
476 obj = self.get(hash_code=hash)
486 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
489 if obj.expiration < datetime.datetime.now():
498 class ValidationHash(models.Model):
499 hash_code = models.CharField(max_length=255, unique=True)
500 seed = models.CharField(max_length=12)
501 expiration = models.DateTimeField(default=one_day_from_now)
502 type = models.CharField(max_length=12)
503 user = models.ForeignKey(User)
505 objects = ValidationHashManager()
508 unique_together = ('user', 'type')
512 return self.hash_code
514 class AuthKeyUserAssociation(models.Model):
515 key = models.CharField(max_length=255, null=False, unique=True)
516 provider = models.CharField(max_length=64)
517 user = models.ForeignKey(User, related_name="auth_keys")
518 added_at = models.DateTimeField(default=datetime.datetime.now)