2 from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
3 from django.contrib.contenttypes.models import ContentType
4 from django.contrib.auth.models import User as DjangoUser, AnonymousUser as DjangoAnonymousUser
5 from django.db.models import Q
7 from hashlib import md5
9 from md5 import new as md5
12 from random import Random
14 from django.utils.translation import ugettext as _
17 QUESTIONS_PER_PAGE_CHOICES = (
23 class AnonymousUser(DjangoAnonymousUser):
24 def get_visible_answers(self, question):
25 return question.answers.filter_state(deleted=False)
27 def can_view_deleted_post(self, post):
30 def can_vote_up(self):
33 def can_vote_down(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_accept_answer(self, answer):
60 def can_create_tags(self):
63 def can_edit_post(self, post):
66 def can_wikify(self, post):
69 def can_cancel_wiki(self, post):
72 def can_retag_questions(self):
75 def can_close_question(self, question):
78 def can_reopen_question(self, question):
81 def can_delete_post(self, post):
84 def can_upload_files(self):
87 def true_if_is_super_or_staff(fn):
88 def decorated(self, *args, **kwargs):
89 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
93 def false_if_validation_required_to(item):
95 def decorated(self, *args, **kwargs):
96 if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
99 return fn(self, *args, **kwargs)
103 class User(BaseModel, DjangoUser):
104 is_approved = models.BooleanField(default=False)
105 email_isvalid = models.BooleanField(default=False)
107 reputation = models.PositiveIntegerField(default=0)
108 gold = models.PositiveIntegerField(default=0)
109 silver = models.PositiveIntegerField(default=0)
110 bronze = models.PositiveIntegerField(default=0)
112 last_seen = models.DateTimeField(default=datetime.datetime.now)
113 real_name = models.CharField(max_length=100, blank=True)
114 website = models.URLField(max_length=200, blank=True)
115 location = models.CharField(max_length=100, blank=True)
116 date_of_birth = models.DateField(null=True, blank=True)
117 about = models.TextField(blank=True)
119 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
121 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
122 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
124 def __unicode__(self):
128 def is_siteowner(self):
129 #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
133 def decorated_name(self):
134 if settings.SHOW_STATUS_DIAMONDS:
135 if self.is_superuser:
136 return u"%s \u2666\u2666" % self.username
139 return u"%s \u2666" % self.username
145 return md5(self.email).hexdigest()
147 def save(self, *args, **kwargs):
148 if self.reputation < 0:
151 new = not bool(self.id)
153 super(User, self).save(*args, **kwargs)
156 sub_settings = SubscriptionSettings(user=self)
159 def get_absolute_url(self):
160 return self.get_profile_url()
162 def get_messages(self):
164 for m in self.message_set.all():
165 messages.append(m.message)
168 def delete_messages(self):
169 self.message_set.all().delete()
172 def get_profile_url(self):
173 return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
175 def get_absolute_url(self):
176 return self.get_profile_url()
178 def get_profile_link(self):
179 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
180 return mark_safe(profile_link)
182 def get_visible_answers(self, question):
183 return question.answers.filter_state(deleted=False)
185 def get_vote_count_today(self):
186 today = datetime.date.today()
187 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
188 action_date__gte=(today - datetime.timedelta(days=1))).count()
190 def get_reputation_by_upvoted_today(self):
191 today = datetime.datetime.now()
192 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
194 #todo: redo this, maybe transform in the daily cap
195 #if sum.get('value__sum', None) is not None: return sum['value__sum']
198 def get_flagged_items_count_today(self):
199 today = datetime.date.today()
200 return self.actions.filter(canceled=False, action_type="flag",
201 action_date__gte=(today - datetime.timedelta(days=1))).count()
203 @true_if_is_super_or_staff
204 def can_view_deleted_post(self, post):
205 return post.author == self
207 @true_if_is_super_or_staff
208 def can_vote_up(self):
209 return self.reputation >= int(settings.REP_TO_VOTE_UP)
211 @true_if_is_super_or_staff
212 def can_vote_down(self):
213 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
215 @false_if_validation_required_to('flag')
216 def can_flag_offensive(self, post=None):
217 if post is not None and post.author == self:
219 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
221 @true_if_is_super_or_staff
222 def can_view_offensive_flags(self, post=None):
223 if post is not None and post.author == self:
225 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
227 @true_if_is_super_or_staff
228 @false_if_validation_required_to('comment')
229 def can_comment(self, post):
230 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
231 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
233 @true_if_is_super_or_staff
234 def can_like_comment(self, comment):
235 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
237 @true_if_is_super_or_staff
238 def can_edit_comment(self, comment):
239 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
240 ) or self.is_superuser
242 @true_if_is_super_or_staff
243 def can_delete_comment(self, comment):
244 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
246 def can_convert_to_comment(self, answer):
247 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
248 (settings.REP_TO_CONVERT_TO_COMMENT))
250 @true_if_is_super_or_staff
251 def can_accept_answer(self, answer):
252 return self == answer.question.author
254 @true_if_is_super_or_staff
255 def can_create_tags(self):
256 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
258 @true_if_is_super_or_staff
259 def can_edit_post(self, post):
260 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
261 ) or (post.nis.wiki and self.reputation >= int(
262 settings.REP_TO_EDIT_WIKI))
264 @true_if_is_super_or_staff
265 def can_wikify(self, post):
266 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
268 @true_if_is_super_or_staff
269 def can_cancel_wiki(self, post):
270 return self == post.author
272 @true_if_is_super_or_staff
273 def can_retag_questions(self):
274 return self.reputation >= int(settings.REP_TO_RETAG)
276 @true_if_is_super_or_staff
277 def can_close_question(self, question):
278 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
279 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
281 @true_if_is_super_or_staff
282 def can_reopen_question(self, question):
283 return self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN
285 @true_if_is_super_or_staff
286 def can_delete_post(self, post):
287 if post.node_type == "comment":
288 return self.can_delete_comment(post)
290 return (self == post.author and (post.__class__.__name__ == "Answer" or
291 not post.answers.exclude(author=self).count()))
293 @true_if_is_super_or_staff
294 def can_upload_files(self):
295 return self.reputation >= int(settings.REP_TO_UPLOAD)
297 def email_valid_and_can_ask(self):
298 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
300 def email_valid_and_can_answer(self):
301 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
303 def check_password(self, old_passwd):
304 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
305 return DjangoUser.check_password(self, old_passwd)
308 def suspension(self):
309 if self.__dict__.get('_suspension_dencache_', False) != None:
311 self.__dict__['_suspension_dencache_'] = self.actions.get(action_type="suspend", canceled=False)
312 except ObjectDoesNotExist:
313 self.__dict__['_suspension_dencache_'] = None
314 except MultipleObjectsReturned:
315 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
316 self.__dict__['_suspension_dencache_'] = self.actions.filter(action_type="suspend", canceled=False
317 ).order_by('-action_date')[0]
319 return self.__dict__['_suspension_dencache_']
321 def _pop_suspension_cache(self):
322 self.__dict__.pop('_suspension_dencache_', None)
324 def is_suspended(self):
325 if not self.is_active:
326 suspension = self.suspension
328 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
329 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
330 days=int(suspension.extra.get('forxdays', 365)))):
340 class SubscriptionSettings(models.Model):
341 user = models.OneToOneField(User, related_name='subscription_settings')
343 enable_notifications = models.BooleanField(default=True)
346 member_joins = models.CharField(max_length=1, default='n')
347 new_question = models.CharField(max_length=1, default='d')
348 new_question_watched_tags = models.CharField(max_length=1, default='i')
349 subscribed_questions = models.CharField(max_length=1, default='i')
352 all_questions = models.BooleanField(default=False)
353 all_questions_watched_tags = models.BooleanField(default=False)
354 questions_asked = models.BooleanField(default=True)
355 questions_answered = models.BooleanField(default=True)
356 questions_commented = models.BooleanField(default=False)
357 questions_viewed = models.BooleanField(default=False)
359 #notify activity on subscribed
360 notify_answers = models.BooleanField(default=True)
361 notify_reply_to_comments = models.BooleanField(default=True)
362 notify_comments_own_post = models.BooleanField(default=True)
363 notify_comments = models.BooleanField(default=False)
364 notify_accepted = models.BooleanField(default=False)
369 from forum.utils.time import one_day_from_now
371 class ValidationHashManager(models.Manager):
372 def _generate_md5_hash(self, user, type, hash_data, seed):
373 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
375 def create_new(self, user, type, hash_data=[], expiration=None):
376 seed = ''.join(Random().sample(string.letters+string.digits, 12))
377 hash = self._generate_md5_hash(user, type, hash_data, seed)
379 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
381 if expiration is not None:
382 obj.expiration = expiration
391 def validate(self, hash, user, type, hash_data=[]):
393 obj = self.get(hash_code=hash)
403 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
406 if obj.expiration < datetime.datetime.now():
415 class ValidationHash(models.Model):
416 hash_code = models.CharField(max_length=255, unique=True)
417 seed = models.CharField(max_length=12)
418 expiration = models.DateTimeField(default=one_day_from_now)
419 type = models.CharField(max_length=12)
420 user = models.ForeignKey(User)
422 objects = ValidationHashManager()
425 unique_together = ('user', 'type')
429 return self.hash_code
431 class AuthKeyUserAssociation(models.Model):
432 key = models.CharField(max_length=255, null=False, unique=True)
433 provider = models.CharField(max_length=64)
434 user = models.ForeignKey(User, related_name="auth_keys")
435 added_at = models.DateTimeField(default=datetime.datetime.now)