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