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