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