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