]> git.openstreetmap.org Git - osqa.git/blob - forum/models/user.py
SPLUNK-128, adding more padding to the content container, now it shouldn't cover...
[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
8 import string
9 from random import Random
10
11 from django.utils.translation import ugettext as _
12 import logging
13
14 class AnonymousUser(DjangoAnonymousUser):
15     reputation = 0
16     
17     def get_visible_answers(self, question):
18         return question.answers.filter_state(deleted=False)
19
20     def can_view_deleted_post(self, post):
21         return False
22
23     def can_vote_up(self):
24         return False
25
26     def can_vote_down(self):
27         return False
28     
29     def can_vote_count_today(self):
30         return 0
31
32     def can_flag_offensive(self, post=None):
33         return False
34
35     def can_view_offensive_flags(self, post=None):
36         return False
37
38     def can_comment(self, post):
39         return False
40
41     def can_like_comment(self, comment):
42         return False
43
44     def can_edit_comment(self, comment):
45         return False
46
47     def can_delete_comment(self, comment):
48         return False
49
50     def can_convert_to_comment(self, answer):
51         return False
52     
53     def can_convert_to_question(self, answer):
54         return False
55     
56     def can_convert_comment_to_answer(self, comment):
57         return False
58
59     def can_accept_answer(self, answer):
60         return False
61
62     def can_create_tags(self):
63         return False
64
65     def can_edit_post(self, post):
66         return False
67
68     def can_wikify(self, post):
69         return False
70
71     def can_cancel_wiki(self, post):
72         return False
73
74     def can_retag_questions(self):
75         return False
76
77     def can_close_question(self, question):
78         return False
79
80     def can_reopen_question(self, question):
81         return False
82
83     def can_delete_post(self, post):
84         return False
85
86     def can_upload_files(self):
87         return False
88
89     def is_a_super_user_or_staff(self):
90         return False
91
92 def true_if_is_super_or_staff(fn):
93     def decorated(self, *args, **kwargs):
94         return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
95
96     return decorated
97
98 def false_if_validation_required_to(item):
99     def decorator(fn):
100         def decorated(self, *args, **kwargs):
101             if item in settings.REQUIRE_EMAIL_VALIDATION_TO and not self.email_isvalid:
102                 return False
103             else:
104                 return fn(self, *args, **kwargs)
105         return decorated
106     return decorator
107
108 class User(BaseModel, DjangoUser):
109     is_approved = models.BooleanField(default=False)
110     email_isvalid = models.BooleanField(default=False)
111
112     reputation = models.PositiveIntegerField(default=0)
113     gold = models.PositiveIntegerField(default=0)
114     silver = models.PositiveIntegerField(default=0)
115     bronze = models.PositiveIntegerField(default=0)
116
117     last_seen = models.DateTimeField(default=datetime.datetime.now)
118     real_name = models.CharField(max_length=100, blank=True)
119     website = models.URLField(max_length=200, blank=True)
120     location = models.CharField(max_length=100, blank=True)
121     date_of_birth = models.DateField(null=True, blank=True)
122     about = models.TextField(blank=True)
123
124     subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
125
126     vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
127     vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
128
129     def __unicode__(self):
130         return self.username
131
132     @property
133     def prop(self):
134         prop = self.__dict__.get('_prop', None)
135
136         if prop is None:
137             prop = UserPropertyDict(self)
138             self._prop = prop
139
140         return prop
141
142     @property
143     def is_siteowner(self):
144         #todo: temporary thing, for now lets just assume that the site owner will always be the first user of the application
145         return self.id == 1
146
147     @property
148     def decorated_name(self):
149         if settings.SHOW_STATUS_DIAMONDS:
150             if self.is_superuser:
151                 return u"%s \u2666\u2666" % self.username
152
153             if self.is_staff:
154                 return u"%s \u2666" % self.username
155
156         return self.username
157
158     @property
159     def last_activity(self):
160         try:
161             return self.actions.order_by('-action_date')[0].action_date
162         except:
163             return self.last_seen
164
165     @property
166     def gravatar(self):
167         return md5(self.email.lower()).hexdigest()
168     
169     def save(self, *args, **kwargs):
170         if self.reputation < 0:
171             self.reputation = 0
172
173         new = not bool(self.id)
174
175         super(User, self).save(*args, **kwargs)
176
177         if new:
178             sub_settings = SubscriptionSettings(user=self)
179             sub_settings.save()
180
181     def get_messages(self):
182         messages = []
183         for m in self.message_set.all():
184             messages.append(m.message)
185         return messages
186
187     def delete_messages(self):
188         self.message_set.all().delete()
189
190     @models.permalink
191     def get_profile_url(self):
192         return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
193
194     def get_absolute_url(self):
195         return self.get_profile_url()
196
197     @models.permalink
198     def get_asked_url(self):
199         return ('user_questions', (), {'mode': _('asked-by'), 'user': self.id, 'slug': slugify(self.username)})
200
201     @models.permalink
202     def get_answered_url(self):
203         return ('user_questions', (), {'mode': _('answered-by'), 'user': self.id, 'slug': slugify(self.username)})
204
205     @models.permalink
206     def get_subscribed_url(self):
207         return ('user_questions', (), {'mode': _('subscribed-by'), 'user': self.id, 'slug': slugify(self.username)})
208
209     def get_profile_link(self):
210         profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
211         return mark_safe(profile_link)
212
213     def get_visible_answers(self, question):
214         return question.answers.filter_state(deleted=False)
215
216     def get_vote_count_today(self):
217         today = datetime.date.today()
218         return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
219                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
220
221     def get_reputation_by_upvoted_today(self):
222         today = datetime.datetime.now()
223         sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
224                 models.Sum('value'))
225         #todo: redo this, maybe transform in the daily cap
226         #if sum.get('value__sum', None) is not None: return sum['value__sum']
227         return 0
228
229     def get_flagged_items_count_today(self):
230         today = datetime.date.today()
231         return self.actions.filter(canceled=False, action_type="flag",
232                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
233     
234     def can_vote_count_today(self):
235         votes_today = settings.MAX_VOTES_PER_DAY
236         
237         if settings.USER_REPUTATION_TO_MAX_VOTES:
238             votes_today = votes_today + int(self.reputation)
239         
240         return votes_today
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_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'