]> git.openstreetmap.org Git - osqa.git/blob - forum/models/user.py
Merge pull request #49 from udacity/login_logout_links
[osqa.git] / forum / models / user.py
1 from base import *
2 from utils import PickledObjectField
3 from django.conf import settings as django_settings
4 from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
5 from django.contrib.contenttypes.models import ContentType
6 from django.contrib.auth.models import User as DjangoUser, AnonymousUser as DjangoAnonymousUser
7 from django.db.models import Q, Manager
8 from django.core.urlresolvers import get_script_prefix
9
10 from django.utils.encoding import smart_unicode
11
12 from forum.settings import TRUNCATE_LONG_USERNAMES, TRUNCATE_USERNAMES_LONGER_THAN
13
14 import string
15 from random import Random
16
17 from django.utils.translation import ugettext as _
18 import logging
19
20 class AnonymousUser(DjangoAnonymousUser):
21     reputation = 0
22     
23     def get_visible_answers(self, question):
24         return question.answers.filter_state(deleted=False)
25
26     def can_view_deleted_post(self, post):
27         return False
28
29     def can_vote_up(self):
30         return False
31
32     def can_vote_down(self):
33         return False
34     
35     def can_vote_count_today(self):
36         return 0
37
38     def can_flag_offensive(self, post=None):
39         return False
40
41     def can_view_offensive_flags(self, post=None):
42         return False
43
44     def can_comment(self, post):
45         return False
46
47     def can_like_comment(self, comment):
48         return False
49
50     def can_edit_comment(self, comment):
51         return False
52
53     def can_delete_comment(self, comment):
54         return False
55
56     def can_convert_to_comment(self, answer):
57         return False
58     
59     def can_convert_to_question(self, answer):
60         return False
61     
62     def can_convert_comment_to_answer(self, comment):
63         return False
64
65     def can_accept_answer(self, answer):
66         return False
67
68     def can_create_tags(self):
69         return False
70
71     def can_edit_post(self, post):
72         return False
73
74     def can_wikify(self, post):
75         return False
76
77     def can_cancel_wiki(self, post):
78         return False
79
80     def can_retag_questions(self):
81         return False
82
83     def can_close_question(self, question):
84         return False
85
86     def can_reopen_question(self, question):
87         return False
88
89     def can_delete_post(self, post):
90         return False
91
92     def can_upload_files(self):
93         return False
94
95     def is_a_super_user_or_staff(self):
96         return False
97
98 def true_if_is_super_or_staff(fn):
99     def decorated(self, *args, **kwargs):
100         return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
101
102     return decorated
103
104 def false_if_validation_required_to(item):
105     def decorator(fn):
106         def decorated(self, *args, **kwargs):
107             if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
108                 return False
109             else:
110                 return fn(self, *args, **kwargs)
111         return decorated
112     return decorator
113
114 class UserManager(CachedManager):
115     def get(self, *args, **kwargs):
116         if not len(args) and len(kwargs) == 1 and 'username' in kwargs:
117             matching_users = self.filter(username=kwargs['username'])
118             
119             if len(matching_users) == 1:
120                 return matching_users[0]
121             elif len(matching_users) > 1:
122                 for user in matching_users:
123                     if user.username == kwargs['username']:
124                         return user
125                 return matching_users[0]
126         return super(UserManager, self).get(*args, **kwargs)
127
128 class User(BaseModel, DjangoUser):
129     is_approved = models.BooleanField(default=False)
130     email_isvalid = models.BooleanField(default=False)
131
132     reputation = models.IntegerField(default=0)
133     gold = models.PositiveIntegerField(default=0)
134     silver = models.PositiveIntegerField(default=0)
135     bronze = models.PositiveIntegerField(default=0)
136
137     last_seen = models.DateTimeField(default=datetime.datetime.now)
138     real_name = models.CharField(max_length=100, blank=True)
139     website = models.URLField(max_length=200, blank=True)
140     location = models.CharField(max_length=100, blank=True)
141     date_of_birth = models.DateField(null=True, blank=True)
142     about = models.TextField(blank=True)
143
144     subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
145
146     vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
147     vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
148
149     objects = UserManager()
150
151     def __unicode__(self):
152         return smart_unicode(self.username)
153
154     @property
155     def prop(self):
156         prop = self.__dict__.get('_prop', None)
157
158         if prop is None:
159             prop = UserPropertyDict(self)
160             self._prop = prop
161
162         return prop
163
164     @property
165     def is_siteowner(self):
166         #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
167         return self.id == 1
168
169
170     def _decorated_name(self):
171         username = smart_unicode(self.username)
172
173         if len(username) > TRUNCATE_USERNAMES_LONGER_THAN and TRUNCATE_LONG_USERNAMES:
174             username = '%s...' % username[:TRUNCATE_USERNAMES_LONGER_THAN-3]
175
176         if settings.SHOW_STATUS_DIAMONDS:
177             if self.is_superuser:
178                 return u"%s \u2666\u2666" % username
179
180             if self.is_staff:
181                 return u"%s \u2666" % username
182
183         return username
184
185     @property
186     def decorated_name(self):
187         return self._decorated_name()
188
189     @property
190     def last_activity(self):
191         try:
192             return self.actions.order_by('-action_date')[0].action_date
193         except:
194             return self.last_seen
195
196     @property
197     def gravatar(self):
198         return md5(self.email.lower()).hexdigest()
199     
200     def save(self, *args, **kwargs):
201         # If the community doesn't allow negative reputation, set it to 0
202         if not settings.ALLOW_NEGATIVE_REPUTATION and self.reputation < 0:
203             self.reputation = 0
204
205         new = not bool(self.id)
206
207         super(User, self).save(*args, **kwargs)
208
209         if new:
210             sub_settings = SubscriptionSettings(user=self)
211             sub_settings.save()
212
213     @models.permalink
214     def get_profile_url(self):
215         keyword_arguments = {
216             'slug': slugify(smart_unicode(self.username))
217         }
218         if settings.INCLUDE_ID_IN_USER_URLS:
219             keyword_arguments.update({
220                 'id': self.id,
221             })
222         return ('user_profile', (), keyword_arguments)
223
224     def get_absolute_url(self):
225         root_relative_url = self.get_profile_url()
226         relative_url = root_relative_url[len(get_script_prefix()):]
227         return '%s/%s' % (django_settings.APP_URL, relative_url)
228
229     @models.permalink
230     def get_asked_url(self):
231         return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
232
233     @models.permalink
234     def get_user_subscriptions_url(self):
235         keyword_arguments = {
236             'slug': slugify(smart_unicode(self.username))
237         }
238         if settings.INCLUDE_ID_IN_USER_URLS:
239             keyword_arguments.update({
240                 'id': self.id,
241             })
242         return ('user_subscriptions', (), keyword_arguments)
243
244     @models.permalink
245     def get_answered_url(self):
246         return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
247
248     def get_subscribed_url(self):
249         try:
250             # Try to retrieve the Subscribed User URL.
251             url = reverse('user_questions',
252                            kwargs={'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(smart_unicode(self.username))})
253             return url
254         except Exception, e:
255             # If some Exception has been raised, don't forget to log it.
256             logging.error("Error retrieving a subscribed user URL: %s" % e)
257
258     def get_profile_link(self):
259         profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
260         return mark_safe(profile_link)
261
262     def get_visible_answers(self, question):
263         return question.answers.filter_state(deleted=False)
264
265     def get_vote_count_today(self):
266         today = datetime.date.today()
267         return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
268                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
269
270     def get_reputation_by_upvoted_today(self):
271         today = datetime.datetime.now()
272         sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
273                 models.Sum('value'))
274         #todo: redo this, maybe transform in the daily cap
275         #if sum.get('value__sum', None) is not None: return sum['value__sum']
276         return 0
277
278     def get_flagged_items_count_today(self):
279         today = datetime.date.today()
280         return self.actions.filter(canceled=False, action_type="flag",
281                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
282     
283     def can_vote_count_today(self):
284         votes_today = settings.MAX_VOTES_PER_DAY
285         
286         if settings.USER_REPUTATION_TO_MAX_VOTES:
287             votes_today = votes_today + int(self.reputation)
288         
289         return votes_today
290     
291     def can_use_canned_comments(self):
292         # The canned comments feature is available only for admins and moderators,
293         # and only if the "Use canned comments" setting is activated in the administration.
294         if (self.is_superuser or self.is_staff) and settings.USE_CANNED_COMMENTS:
295             return True
296         else:
297             return False
298
299     @true_if_is_super_or_staff
300     def can_view_deleted_post(self, post):
301         return post.author == self
302
303     @true_if_is_super_or_staff
304     def can_vote_up(self):
305         return self.reputation >= int(settings.REP_TO_VOTE_UP)
306
307     @true_if_is_super_or_staff
308     def can_vote_down(self):
309         return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
310
311     @false_if_validation_required_to('flag')
312     def can_flag_offensive(self, post=None):
313         if post is not None and post.author == self:
314             return False
315         return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
316
317     @true_if_is_super_or_staff
318     def can_view_offensive_flags(self, post=None):
319         if post is not None and post.author == self:
320             return True
321         return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
322
323     @true_if_is_super_or_staff
324     @false_if_validation_required_to('comment')
325     def can_comment(self, post):
326         return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
327                 ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
328
329     @true_if_is_super_or_staff
330     def can_like_comment(self, comment):
331         return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
332
333     @true_if_is_super_or_staff
334     def can_edit_comment(self, comment):
335         return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
336         ) or self.is_superuser
337
338     @true_if_is_super_or_staff
339     def can_delete_comment(self, comment):
340         return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
341
342     def can_convert_comment_to_answer(self, comment):
343         # We need to know what is the comment parent node type.
344         comment_parent_type = comment.parent.node_type
345
346         # If the parent is not a question or an answer this comment cannot be converted to an answer.
347         if comment_parent_type != "question" and comment_parent_type != "answer":
348             return False
349
350         return (comment.parent.node_type in ('question', 'answer')) and (self.is_superuser or self.is_staff or (
351             self == comment.author) or (self.reputation >= int(settings.REP_TO_CONVERT_COMMENTS_TO_ANSWERS)))
352
353     def can_convert_to_comment(self, answer):
354         return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
355                 (settings.REP_TO_CONVERT_TO_COMMENT))
356     
357     def can_convert_to_question(self, node):
358         return (not node.marked) and (self.is_superuser or self.is_staff or node.author == self or self.reputation >= int
359                 (settings.REP_TO_CONVERT_TO_QUESTION))
360
361     @true_if_is_super_or_staff
362     def can_accept_answer(self, answer):
363         return self == answer.question.author and (settings.USERS_CAN_ACCEPT_OWN or answer.author != answer.question.author)
364
365     @true_if_is_super_or_staff
366     def can_create_tags(self):
367         return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
368
369     @true_if_is_super_or_staff
370     def can_edit_post(self, post):
371         return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
372                                                              ) or (post.nis.wiki and self.reputation >= int(
373                 settings.REP_TO_EDIT_WIKI))
374
375     @true_if_is_super_or_staff
376     def can_wikify(self, post):
377         return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
378
379     @true_if_is_super_or_staff
380     def can_cancel_wiki(self, post):
381         return self == post.author
382
383     @true_if_is_super_or_staff
384     def can_retag_questions(self):
385         return self.reputation >= int(settings.REP_TO_RETAG)
386
387     @true_if_is_super_or_staff
388     def can_close_question(self, question):
389         return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
390         ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
391
392     @true_if_is_super_or_staff
393     def can_reopen_question(self, question):
394         # Check whether the setting to Unify close and reopen permissions has been activated
395         if bool(settings.UNIFY_PERMISSIONS_TO_CLOSE_AND_REOPEN):
396             # If we unify close to reopen check whether the user has permissions to close.
397             # If he has -- he can reopen his question too.
398             can_reopen = (
399                 self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
400             ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
401         else:
402             # Check whether the user is the author and has the required permissions to reopen
403             can_reopen = self == question.author and self.reputation >= int(settings.REP_TO_REOPEN_OWN)
404         return can_reopen
405
406     @true_if_is_super_or_staff
407     def can_delete_post(self, post):
408         if post.node_type == "comment":
409             return self.can_delete_comment(post)
410
411         return (self == post.author and (post.__class__.__name__ == "Answer" or
412         not post.answers.exclude(author__id=self.id).count()))
413
414     @true_if_is_super_or_staff
415     def can_upload_files(self):
416         return self.reputation >= int(settings.REP_TO_UPLOAD)
417
418     @true_if_is_super_or_staff
419     def is_a_super_user_or_staff(self):
420         return False
421
422     def email_valid_and_can_ask(self):
423         return 'ask' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
424
425     def email_valid_and_can_answer(self):
426         return 'answer' not in settings.REQUIRE_EMAIL_VALIDATION_TO or self.email_isvalid
427
428     def check_password(self, old_passwd):
429         self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
430         return DjangoUser.check_password(self, old_passwd)
431
432     @property
433     def suspension(self):
434         if self.__dict__.get('_suspension_dencache_', False) != None:
435             try:
436                 self.__dict__['_suspension_dencache_'] = self.reputes.get(action__action_type="suspend", action__canceled=False).action
437             except ObjectDoesNotExist:
438                 self.__dict__['_suspension_dencache_'] = None
439             except MultipleObjectsReturned:
440                 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
441                 self.__dict__['_suspension_dencache_'] = self.reputes.filter(action__action_type="suspend", action__canceled=False
442                                                                              ).order_by('-action__action_date')[0].action
443
444         return self.__dict__['_suspension_dencache_']
445
446     def _pop_suspension_cache(self):
447         self.__dict__.pop('_suspension_dencache_', None)
448
449     def is_suspended(self):
450         if not self.is_active:
451             suspension = self.suspension
452
453             if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
454             datetime.datetime.now() > suspension.action_date + datetime.timedelta(
455                     days=int(suspension.extra.get('forxdays', 365)))):
456                 suspension.cancel()
457             else:
458                 return True
459
460         return False
461
462     class Meta:
463         app_label = 'forum'
464
465 class UserProperty(BaseModel):
466     user = models.ForeignKey(User, related_name='properties')
467     key = models.CharField(max_length=16)
468     value = PickledObjectField()
469
470     class Meta:
471         app_label = 'forum'
472         unique_together = ('user', 'key')
473
474     def cache_key(self):
475         return self._generate_cache_key("%s:%s" % (self.user.id, self.key))
476
477     @classmethod
478     def infer_cache_key(cls, querydict):
479         if 'user' in querydict and 'key' in querydict:
480             cache_key = cls._generate_cache_key("%s:%s" % (querydict['user'].id, querydict['key']))
481             if len(cache_key) > django_settings.CACHE_MAX_KEY_LENGTH:
482                 cache_key = cache_key[:django_settings.CACHE_MAX_KEY_LENGTH]
483             return cache_key
484
485         return None
486
487 class UserPropertyDict(object):
488     def __init__(self, user):
489         self.__dict__['_user'] = user
490
491     def __get_property(self, name):
492         if self.__dict__.get('__%s__' % name, None):
493             return self.__dict__['__%s__' % name]
494         try:
495             user = self.__dict__['_user']
496             prop = UserProperty.objects.get(user=user, key=name)
497             self.__dict__['__%s__' % name] = prop
498             self.__dict__[name] = prop.value
499             return prop
500         except:
501             return None
502
503
504     def __getattr__(self, name):
505         if self.__dict__.get(name, None):
506             return self.__dict__[name]
507
508         prop = self.__get_property(name)
509
510         if prop:
511             return prop.value
512         else:
513             return None
514
515     def __setattr__(self, name, value):
516         current = self.__get_property(name)
517
518         if value is not None:
519             if current:
520                 current.value = value
521                 self.__dict__[name] = value
522                 current.save(full_save=True)
523             else:
524                 user = self.__dict__['_user']
525                 prop = UserProperty(user=user, value=value, key=name)
526                 prop.save()
527                 self.__dict__[name] = value
528                 self.__dict__['__%s__' % name] = prop
529         else:
530             if current:
531                 current.delete()
532                 del self.__dict__[name]
533                 del self.__dict__['__%s__' % name]
534
535
536 class SubscriptionSettings(models.Model):
537     user = models.OneToOneField(User, related_name='subscription_settings', editable=False)
538
539     enable_notifications = models.BooleanField(default=True)
540
541     #notify if
542     member_joins = models.CharField(max_length=1, default='n')
543     new_question = models.CharField(max_length=1, default='n')
544     new_question_watched_tags = models.CharField(max_length=1, default='i')
545     subscribed_questions = models.CharField(max_length=1, default='i')
546
547     #auto_subscribe_to
548     all_questions = models.BooleanField(default=False)
549     all_questions_watched_tags = models.BooleanField(default=False)
550     questions_viewed = models.BooleanField(default=False)
551
552     #notify activity on subscribed
553     notify_answers = models.BooleanField(default=True)
554     notify_reply_to_comments = models.BooleanField(default=True)
555     notify_comments_own_post = models.BooleanField(default=True)
556     notify_comments = models.BooleanField(default=False)
557     notify_accepted = models.BooleanField(default=False)
558
559     send_digest = models.BooleanField(default=True)
560
561     class Meta:
562         app_label = 'forum'
563
564 from forum.utils.time import one_day_from_now
565
566 class ValidationHashManager(models.Manager):
567     def _generate_md5_hash(self, user, type, hash_data, seed):
568         return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
569
570     def create_new(self, user, type, hash_data=[], expiration=None):
571         seed = ''.join(Random().sample(string.letters+string.digits, 12))
572         hash = self._generate_md5_hash(user, type, hash_data, seed)
573
574         obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
575
576         if expiration is not None:
577             obj.expiration = expiration
578
579         try:
580             obj.save()
581         except:
582             return None
583
584         return obj
585
586     def validate(self, hash, user, type, hash_data=[]):
587         try:
588             obj = self.get(hash_code=hash)
589         except:
590             return False
591
592         if obj.type != type:
593             return False
594
595         if obj.user != user:
596             return False
597
598         valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
599
600         if valid:
601             if obj.expiration < datetime.datetime.now():
602                 obj.delete()
603                 return False
604             else:
605                 obj.delete()
606                 return True
607
608         return False
609
610 class ValidationHash(models.Model):
611     hash_code = models.CharField(max_length=255, unique=True)
612     seed = models.CharField(max_length=12)
613     expiration = models.DateTimeField(default=one_day_from_now)
614     type = models.CharField(max_length=12)
615     user = models.ForeignKey(User)
616
617     objects = ValidationHashManager()
618
619     class Meta:
620         unique_together = ('user', 'type')
621         app_label = 'forum'
622
623     def __str__(self):
624         return self.hash_code
625
626 class AuthKeyUserAssociation(models.Model):
627     key = models.CharField(max_length=255, null=False, unique=True)
628     provider = models.CharField(max_length=64)
629     user = models.ForeignKey(User, related_name="auth_keys")
630     added_at = models.DateTimeField(default=datetime.datetime.now)
631
632     class Meta:
633         app_label = 'forum'