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