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