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