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