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