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