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
134 return md5(self.email).hexdigest()
136 def save(self, *args, **kwargs):
137 if self.reputation < 0:
140 new = not bool(self.id)
142 super(User, self).save(*args, **kwargs)
145 sub_settings = SubscriptionSettings(user=self)
148 def get_absolute_url(self):
149 return self.get_profile_url()
151 def get_messages(self):
153 for m in self.message_set.all():
154 messages.append(m.message)
157 def delete_messages(self):
158 self.message_set.all().delete()
161 def get_profile_url(self):
162 return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
164 def get_absolute_url(self):
165 return self.get_profile_url()
167 def get_profile_link(self):
168 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
169 return mark_safe(profile_link)
171 def get_visible_answers(self, question):
172 return question.answers.filter_state(deleted=False)
174 def get_vote_count_today(self):
175 today = datetime.date.today()
176 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
177 action_date__gte=(today - datetime.timedelta(days=1))).count()
179 def get_reputation_by_upvoted_today(self):
180 today = datetime.datetime.now()
181 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
183 #todo: redo this, maybe transform in the daily cap
184 #if sum.get('value__sum', None) is not None: return sum['value__sum']
187 def get_flagged_items_count_today(self):
188 today = datetime.date.today()
189 return self.actions.filter(canceled=False, action_type="flag",
190 action_date__gte=(today - datetime.timedelta(days=1))).count()
192 @true_if_is_super_or_staff
193 def can_view_deleted_post(self, post):
194 return post.author == self
196 @true_if_is_super_or_staff
197 def can_vote_up(self):
198 return self.reputation >= int(settings.REP_TO_VOTE_UP)
200 @true_if_is_super_or_staff
201 def can_vote_down(self):
202 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
204 @false_if_validation_required_to('flag')
205 def can_flag_offensive(self, post=None):
206 if post is not None and post.author == self:
208 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
210 @true_if_is_super_or_staff
211 def can_view_offensive_flags(self, post=None):
212 if post is not None and post.author == self:
214 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
216 @true_if_is_super_or_staff
217 @false_if_validation_required_to('comment')
218 def can_comment(self, post):
219 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
220 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
222 @true_if_is_super_or_staff
223 def can_like_comment(self, comment):
224 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
226 @true_if_is_super_or_staff
227 def can_edit_comment(self, comment):
228 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
229 ) or self.is_superuser
231 @true_if_is_super_or_staff
232 def can_delete_comment(self, comment):
233 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
235 def can_convert_to_comment(self, answer):
236 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
237 (settings.REP_TO_CONVERT_TO_COMMENT))
239 @true_if_is_super_or_staff
240 def can_accept_answer(self, answer):
241 return self == answer.question.author
243 @true_if_is_super_or_staff
244 def can_create_tags(self):
245 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
247 @true_if_is_super_or_staff
248 def can_edit_post(self, post):
249 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
250 ) or (post.nis.wiki and self.reputation >= int(
251 settings.REP_TO_EDIT_WIKI))
253 @true_if_is_super_or_staff
254 def can_wikify(self, post):
255 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
257 @true_if_is_super_or_staff
258 def can_cancel_wiki(self, post):
259 return self == post.author
261 @true_if_is_super_or_staff
262 def can_retag_questions(self):
263 return self.reputation >= int(settings.REP_TO_RETAG)
265 @true_if_is_super_or_staff
266 def can_close_question(self, question):
267 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
268 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
270 @true_if_is_super_or_staff
271 def can_reopen_question(self, question):
272 return self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN
274 @true_if_is_super_or_staff
275 def can_delete_post(self, post):
276 if post.node_type == "comment":
277 return self.can_delete_comment(post)
279 return (self == post.author and (post.__class__.__name__ == "Answer" or
280 not post.answers.exclude(author=self).count()))
282 @true_if_is_super_or_staff
283 def can_upload_files(self):
284 return self.reputation >= int(settings.REP_TO_UPLOAD)
286 def email_valid_and_can_ask(self):
287 return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
289 def email_valid_and_can_answer(self):
290 return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
292 def check_password(self, old_passwd):
293 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
294 return DjangoUser.check_password(self, old_passwd)
297 def suspension(self):
298 if self.__dict__.get('_suspension_dencache_', False) != None:
300 self.__dict__['_suspension_dencache_'] = self.actions.get(action_type="suspend", canceled=False)
301 except ObjectDoesNotExist:
302 self.__dict__['_suspension_dencache_'] = None
303 except MultipleObjectsReturned:
304 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
305 self.__dict__['_suspension_dencache_'] = self.actions.filter(action_type="suspend", canceled=False
306 ).order_by('-action_date')[0]
308 return self.__dict__['_suspension_dencache_']
310 def _pop_suspension_cache(self):
311 self.__dict__.pop('_suspension_dencache_', None)
313 def is_suspended(self):
314 if not self.is_active:
315 suspension = self.suspension
317 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
318 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
319 days=int(suspension.extra.get('forxdays', 365)))):
329 class SubscriptionSettings(models.Model):
330 user = models.OneToOneField(User, related_name='subscription_settings')
332 enable_notifications = models.BooleanField(default=True)
335 member_joins = models.CharField(max_length=1, default='n')
336 new_question = models.CharField(max_length=1, default='d')
337 new_question_watched_tags = models.CharField(max_length=1, default='i')
338 subscribed_questions = models.CharField(max_length=1, default='i')
341 all_questions = models.BooleanField(default=False)
342 all_questions_watched_tags = models.BooleanField(default=False)
343 questions_asked = models.BooleanField(default=True)
344 questions_answered = models.BooleanField(default=True)
345 questions_commented = models.BooleanField(default=False)
346 questions_viewed = models.BooleanField(default=False)
348 #notify activity on subscribed
349 notify_answers = models.BooleanField(default=True)
350 notify_reply_to_comments = models.BooleanField(default=True)
351 notify_comments_own_post = models.BooleanField(default=True)
352 notify_comments = models.BooleanField(default=False)
353 notify_accepted = models.BooleanField(default=False)
358 from forum.utils.time import one_day_from_now
360 class ValidationHashManager(models.Manager):
361 def _generate_md5_hash(self, user, type, hash_data, seed):
362 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
364 def create_new(self, user, type, hash_data=[], expiration=None):
365 seed = ''.join(Random().sample(string.letters+string.digits, 12))
366 hash = self._generate_md5_hash(user, type, hash_data, seed)
368 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
370 if expiration is not None:
371 obj.expiration = expiration
380 def validate(self, hash, user, type, hash_data=[]):
382 obj = self.get(hash_code=hash)
392 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
395 if obj.expiration < datetime.datetime.now():
404 class ValidationHash(models.Model):
405 hash_code = models.CharField(max_length=255, unique=True)
406 seed = models.CharField(max_length=12)
407 expiration = models.DateTimeField(default=one_day_from_now)
408 type = models.CharField(max_length=12)
409 user = models.ForeignKey(User)
411 objects = ValidationHashManager()
414 unique_together = ('user', 'type')
418 return self.hash_code
420 class AuthKeyUserAssociation(models.Model):
421 key = models.CharField(max_length=255, null=False, unique=True)
422 provider = models.CharField(max_length=64)
423 user = models.ForeignKey(User, related_name="auth_keys")
424 added_at = models.DateTimeField(default=datetime.datetime.now)