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 UserManager(CachedManager):
24 def get_site_owner(self):
25 return self.all().order_by('date_joined')[0]
27 class AnonymousUser(DjangoAnonymousUser):
28 def get_visible_answers(self, question):
29 return question.answers.filter_state(deleted=False)
31 def can_view_deleted_post(self, post):
34 def can_vote_up(self):
37 def can_vote_down(self):
40 def can_flag_offensive(self, post=None):
43 def can_view_offensive_flags(self, post=None):
46 def can_comment(self, post):
49 def can_like_comment(self, comment):
52 def can_edit_comment(self, comment):
55 def can_delete_comment(self, comment):
58 def can_convert_to_comment(self, answer):
61 def can_accept_answer(self, answer):
64 def can_create_tags(self):
67 def can_edit_post(self, post):
70 def can_wikify(self, post):
73 def can_cancel_wiki(self, post):
76 def can_retag_questions(self):
79 def can_close_question(self, question):
82 def can_reopen_question(self, question):
85 def can_delete_post(self, post):
88 def can_upload_files(self):
91 def true_if_is_super_or_staff(fn):
92 def decorated(self, *args, **kwargs):
93 return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
97 class User(BaseModel, DjangoUser):
98 is_approved = models.BooleanField(default=False)
99 email_isvalid = models.BooleanField(default=False)
101 reputation = models.PositiveIntegerField(default=0)
102 gold = models.PositiveIntegerField(default=0)
103 silver = models.PositiveIntegerField(default=0)
104 bronze = models.PositiveIntegerField(default=0)
106 last_seen = models.DateTimeField(default=datetime.datetime.now)
107 real_name = models.CharField(max_length=100, blank=True)
108 website = models.URLField(max_length=200, blank=True)
109 location = models.CharField(max_length=100, blank=True)
110 date_of_birth = models.DateField(null=True, blank=True)
111 about = models.TextField(blank=True)
113 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
115 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
116 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
118 objects = UserManager()
120 def __unicode__(self):
125 return md5(self.email).hexdigest()
127 def save(self, *args, **kwargs):
128 if self.reputation < 0:
131 new = not bool(self.id)
133 super(User, self).save(*args, **kwargs)
136 sub_settings = SubscriptionSettings(user=self)
139 def get_absolute_url(self):
140 return self.get_profile_url()
142 def get_messages(self):
144 for m in self.message_set.all():
145 messages.append(m.message)
148 def delete_messages(self):
149 self.message_set.all().delete()
152 def get_profile_url(self):
153 return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
155 def get_absolute_url(self):
156 return self.get_profile_url()
158 def get_profile_link(self):
159 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
160 return mark_safe(profile_link)
162 def get_visible_answers(self, question):
163 return question.answers.filter_state(deleted=False)
165 def get_vote_count_today(self):
166 today = datetime.date.today()
167 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
168 action_date__gte=(today - datetime.timedelta(days=1))).count()
170 def get_reputation_by_upvoted_today(self):
171 today = datetime.datetime.now()
172 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
174 #todo: redo this, maybe transform in the daily cap
175 #if sum.get('value__sum', None) is not None: return sum['value__sum']
178 def get_flagged_items_count_today(self):
179 today = datetime.date.today()
180 return self.actions.filter(canceled=False, action_type="flag",
181 action_date__gte=(today - datetime.timedelta(days=1))).count()
183 @true_if_is_super_or_staff
184 def can_view_deleted_post(self, post):
185 return post.author == self
187 @true_if_is_super_or_staff
188 def can_vote_up(self):
189 return self.reputation >= int(settings.REP_TO_VOTE_UP)
191 @true_if_is_super_or_staff
192 def can_vote_down(self):
193 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
195 def can_flag_offensive(self, post=None):
196 if post is not None and post.author == self:
198 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
200 @true_if_is_super_or_staff
201 def can_view_offensive_flags(self, post=None):
202 if post is not None and post.author == self:
204 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
206 @true_if_is_super_or_staff
207 def can_comment(self, post):
208 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
209 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
211 @true_if_is_super_or_staff
212 def can_like_comment(self, comment):
213 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
215 @true_if_is_super_or_staff
216 def can_edit_comment(self, comment):
217 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
218 ) or self.is_superuser
220 @true_if_is_super_or_staff
221 def can_delete_comment(self, comment):
222 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
224 def can_convert_to_comment(self, answer):
225 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
226 (settings.REP_TO_CONVERT_TO_COMMENT))
228 @true_if_is_super_or_staff
229 def can_accept_answer(self, answer):
230 return self == answer.question.author
232 @true_if_is_super_or_staff
233 def can_create_tags(self):
234 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
236 @true_if_is_super_or_staff
237 def can_edit_post(self, post):
238 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
239 ) or (post.nis.wiki and self.reputation >= int(
240 settings.REP_TO_EDIT_WIKI))
242 @true_if_is_super_or_staff
243 def can_wikify(self, post):
244 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
246 @true_if_is_super_or_staff
247 def can_cancel_wiki(self, post):
248 return self == post.author
250 @true_if_is_super_or_staff
251 def can_retag_questions(self):
252 return self.reputation >= int(settings.REP_TO_RETAG)
254 @true_if_is_super_or_staff
255 def can_close_question(self, question):
256 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
257 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
259 @true_if_is_super_or_staff
260 def can_reopen_question(self, question):
261 return self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN
263 @true_if_is_super_or_staff
264 def can_delete_post(self, post):
265 if post.node_type == "comment":
266 return self.can_delete_comment(post)
268 return (self == post.author and (post.__class__.__name__ == "Answer" or
269 not post.answers.exclude(author=self).count()))
271 @true_if_is_super_or_staff
272 def can_upload_files(self):
273 return self.reputation >= int(settings.REP_TO_UPLOAD)
275 def check_password(self, old_passwd):
276 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
277 return DjangoUser.check_password(self, old_passwd)
280 def suspension(self):
281 if self.__dict__.get('_suspension_dencache_', False) != None:
283 self.__dict__['_suspension_dencache_'] = self.actions.get(action_type="suspend", canceled=False)
284 except ObjectDoesNotExist:
285 self.__dict__['_suspension_dencache_'] = None
286 except MultipleObjectsReturned:
287 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
288 self.__dict__['_suspension_dencache_'] = self.actions.filter(action_type="suspend", canceled=False
289 ).order_by('-action_date')[0]
291 return self.__dict__['_suspension_dencache_']
293 def _pop_suspension_cache(self):
294 self.__dict__.pop('_suspension_dencache_', None)
296 def is_suspended(self):
297 if not self.is_active:
298 suspension = self.suspension
300 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
301 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
302 days=int(suspension.extra.get('forxdays', 365)))):
312 class SubscriptionSettings(models.Model):
313 user = models.OneToOneField(User, related_name='subscription_settings')
315 enable_notifications = models.BooleanField(default=True)
318 member_joins = models.CharField(max_length=1, default='n')
319 new_question = models.CharField(max_length=1, default='d')
320 new_question_watched_tags = models.CharField(max_length=1, default='i')
321 subscribed_questions = models.CharField(max_length=1, default='i')
324 all_questions = models.BooleanField(default=False)
325 all_questions_watched_tags = models.BooleanField(default=False)
326 questions_asked = models.BooleanField(default=True)
327 questions_answered = models.BooleanField(default=True)
328 questions_commented = models.BooleanField(default=False)
329 questions_viewed = models.BooleanField(default=False)
331 #notify activity on subscribed
332 notify_answers = models.BooleanField(default=True)
333 notify_reply_to_comments = models.BooleanField(default=True)
334 notify_comments_own_post = models.BooleanField(default=True)
335 notify_comments = models.BooleanField(default=False)
336 notify_accepted = models.BooleanField(default=False)
341 from forum.utils.time import one_day_from_now
343 class ValidationHashManager(models.Manager):
344 def _generate_md5_hash(self, user, type, hash_data, seed):
345 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
347 def create_new(self, user, type, hash_data=[], expiration=None):
348 seed = ''.join(Random().sample(string.letters+string.digits, 12))
349 hash = self._generate_md5_hash(user, type, hash_data, seed)
351 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
353 if expiration is not None:
354 obj.expiration = expiration
363 def validate(self, hash, user, type, hash_data=[]):
365 obj = self.get(hash_code=hash)
375 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
378 if obj.expiration < datetime.datetime.now():
387 class ValidationHash(models.Model):
388 hash_code = models.CharField(max_length=255, unique=True)
389 seed = models.CharField(max_length=12)
390 expiration = models.DateTimeField(default=one_day_from_now)
391 type = models.CharField(max_length=12)
392 user = models.ForeignKey(User)
394 objects = ValidationHashManager()
397 unique_together = ('user', 'type')
401 return self.hash_code
403 class AuthKeyUserAssociation(models.Model):
404 key = models.CharField(max_length=255, null=False, unique=True)
405 provider = models.CharField(max_length=64)
406 user = models.ForeignKey(User, related_name="auth_keys")
407 added_at = models.DateTimeField(default=datetime.datetime.now)