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 class User(BaseModel, DjangoUser):
94 is_approved = models.BooleanField(default=False)
95 email_isvalid = models.BooleanField(default=False)
97 reputation = models.PositiveIntegerField(default=0)
98 gold = models.PositiveIntegerField(default=0)
99 silver = models.PositiveIntegerField(default=0)
100 bronze = models.PositiveIntegerField(default=0)
102 last_seen = models.DateTimeField(default=datetime.datetime.now)
103 real_name = models.CharField(max_length=100, blank=True)
104 website = models.URLField(max_length=200, blank=True)
105 location = models.CharField(max_length=100, blank=True)
106 date_of_birth = models.DateField(null=True, blank=True)
107 about = models.TextField(blank=True)
109 subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
111 vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
112 vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
114 def __unicode__(self):
118 def is_siteowner(self):
119 #temporary thing, for now lets just assume that the site owner will always be the first user of the application
124 return md5(self.email).hexdigest()
126 def save(self, *args, **kwargs):
127 if self.reputation < 0:
130 new = not bool(self.id)
132 super(User, self).save(*args, **kwargs)
135 sub_settings = SubscriptionSettings(user=self)
138 def get_absolute_url(self):
139 return self.get_profile_url()
141 def get_messages(self):
143 for m in self.message_set.all():
144 messages.append(m.message)
147 def delete_messages(self):
148 self.message_set.all().delete()
151 def get_profile_url(self):
152 return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
154 def get_absolute_url(self):
155 return self.get_profile_url()
157 def get_profile_link(self):
158 profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
159 return mark_safe(profile_link)
161 def get_visible_answers(self, question):
162 return question.answers.filter_state(deleted=False)
164 def get_vote_count_today(self):
165 today = datetime.date.today()
166 return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
167 action_date__gte=(today - datetime.timedelta(days=1))).count()
169 def get_reputation_by_upvoted_today(self):
170 today = datetime.datetime.now()
171 sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
173 #todo: redo this, maybe transform in the daily cap
174 #if sum.get('value__sum', None) is not None: return sum['value__sum']
177 def get_flagged_items_count_today(self):
178 today = datetime.date.today()
179 return self.actions.filter(canceled=False, action_type="flag",
180 action_date__gte=(today - datetime.timedelta(days=1))).count()
182 @true_if_is_super_or_staff
183 def can_view_deleted_post(self, post):
184 return post.author == self
186 @true_if_is_super_or_staff
187 def can_vote_up(self):
188 return self.reputation >= int(settings.REP_TO_VOTE_UP)
190 @true_if_is_super_or_staff
191 def can_vote_down(self):
192 return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
194 def can_flag_offensive(self, post=None):
195 if post is not None and post.author == self:
197 return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
199 @true_if_is_super_or_staff
200 def can_view_offensive_flags(self, post=None):
201 if post is not None and post.author == self:
203 return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
205 @true_if_is_super_or_staff
206 def can_comment(self, post):
207 return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
208 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
210 @true_if_is_super_or_staff
211 def can_like_comment(self, comment):
212 return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
214 @true_if_is_super_or_staff
215 def can_edit_comment(self, comment):
216 return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
217 ) or self.is_superuser
219 @true_if_is_super_or_staff
220 def can_delete_comment(self, comment):
221 return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
223 def can_convert_to_comment(self, answer):
224 return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
225 (settings.REP_TO_CONVERT_TO_COMMENT))
227 @true_if_is_super_or_staff
228 def can_accept_answer(self, answer):
229 return self == answer.question.author
231 @true_if_is_super_or_staff
232 def can_create_tags(self):
233 return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
235 @true_if_is_super_or_staff
236 def can_edit_post(self, post):
237 return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
238 ) or (post.nis.wiki and self.reputation >= int(
239 settings.REP_TO_EDIT_WIKI))
241 @true_if_is_super_or_staff
242 def can_wikify(self, post):
243 return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
245 @true_if_is_super_or_staff
246 def can_cancel_wiki(self, post):
247 return self == post.author
249 @true_if_is_super_or_staff
250 def can_retag_questions(self):
251 return self.reputation >= int(settings.REP_TO_RETAG)
253 @true_if_is_super_or_staff
254 def can_close_question(self, question):
255 return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
256 ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
258 @true_if_is_super_or_staff
259 def can_reopen_question(self, question):
260 return self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN
262 @true_if_is_super_or_staff
263 def can_delete_post(self, post):
264 if post.node_type == "comment":
265 return self.can_delete_comment(post)
267 return (self == post.author and (post.__class__.__name__ == "Answer" or
268 not post.answers.exclude(author=self).count()))
270 @true_if_is_super_or_staff
271 def can_upload_files(self):
272 return self.reputation >= int(settings.REP_TO_UPLOAD)
274 def check_password(self, old_passwd):
275 self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
276 return DjangoUser.check_password(self, old_passwd)
279 def suspension(self):
280 if self.__dict__.get('_suspension_dencache_', False) != None:
282 self.__dict__['_suspension_dencache_'] = self.actions.get(action_type="suspend", canceled=False)
283 except ObjectDoesNotExist:
284 self.__dict__['_suspension_dencache_'] = None
285 except MultipleObjectsReturned:
286 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
287 self.__dict__['_suspension_dencache_'] = self.actions.filter(action_type="suspend", canceled=False
288 ).order_by('-action_date')[0]
290 return self.__dict__['_suspension_dencache_']
292 def _pop_suspension_cache(self):
293 self.__dict__.pop('_suspension_dencache_', None)
295 def is_suspended(self):
296 if not self.is_active:
297 suspension = self.suspension
299 if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
300 datetime.datetime.now() > suspension.action_date + datetime.timedelta(
301 days=int(suspension.extra.get('forxdays', 365)))):
311 class SubscriptionSettings(models.Model):
312 user = models.OneToOneField(User, related_name='subscription_settings')
314 enable_notifications = models.BooleanField(default=True)
317 member_joins = models.CharField(max_length=1, default='n')
318 new_question = models.CharField(max_length=1, default='d')
319 new_question_watched_tags = models.CharField(max_length=1, default='i')
320 subscribed_questions = models.CharField(max_length=1, default='i')
323 all_questions = models.BooleanField(default=False)
324 all_questions_watched_tags = models.BooleanField(default=False)
325 questions_asked = models.BooleanField(default=True)
326 questions_answered = models.BooleanField(default=True)
327 questions_commented = models.BooleanField(default=False)
328 questions_viewed = models.BooleanField(default=False)
330 #notify activity on subscribed
331 notify_answers = models.BooleanField(default=True)
332 notify_reply_to_comments = models.BooleanField(default=True)
333 notify_comments_own_post = models.BooleanField(default=True)
334 notify_comments = models.BooleanField(default=False)
335 notify_accepted = models.BooleanField(default=False)
340 from forum.utils.time import one_day_from_now
342 class ValidationHashManager(models.Manager):
343 def _generate_md5_hash(self, user, type, hash_data, seed):
344 return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
346 def create_new(self, user, type, hash_data=[], expiration=None):
347 seed = ''.join(Random().sample(string.letters+string.digits, 12))
348 hash = self._generate_md5_hash(user, type, hash_data, seed)
350 obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
352 if expiration is not None:
353 obj.expiration = expiration
362 def validate(self, hash, user, type, hash_data=[]):
364 obj = self.get(hash_code=hash)
374 valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
377 if obj.expiration < datetime.datetime.now():
386 class ValidationHash(models.Model):
387 hash_code = models.CharField(max_length=255, unique=True)
388 seed = models.CharField(max_length=12)
389 expiration = models.DateTimeField(default=one_day_from_now)
390 type = models.CharField(max_length=12)
391 user = models.ForeignKey(User)
393 objects = ValidationHashManager()
396 unique_together = ('user', 'type')
400 return self.hash_code
402 class AuthKeyUserAssociation(models.Model):
403 key = models.CharField(max_length=255, null=False, unique=True)
404 provider = models.CharField(max_length=64)
405 user = models.ForeignKey(User, related_name="auth_keys")
406 added_at = models.DateTimeField(default=datetime.datetime.now)