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