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