]> git.openstreetmap.org Git - osqa.git/blob - forum/models/user.py
More polished PAI for module html injection and added a couple more places to inject...
[osqa.git] / forum / models / user.py
1 from base import *
2 from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
3 from django.contrib.contenttypes.models import ContentType
4 from django.contrib.auth.models import User as DjangoUser, AnonymousUser as DjangoAnonymousUser
5 from django.db.models import Q
6 try:
7     from hashlib import md5
8 except:
9     from md5 import new as md5
10
11 import string
12 from random import Random
13
14 from django.utils.translation import ugettext as _
15 import logging
16
17 QUESTIONS_PER_PAGE_CHOICES = (
18 (10, u'10'),
19 (30, u'30'),
20 (50, u'50'),
21 )
22
23 class AnonymousUser(DjangoAnonymousUser):
24     def get_visible_answers(self, question):
25         return question.answers.filter_state(deleted=False)
26
27     def can_view_deleted_post(self, post):
28         return False
29
30     def can_vote_up(self):
31         return False
32
33     def can_vote_down(self):
34         return False
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_accept_answer(self, answer):
58         return False
59
60     def can_create_tags(self):
61         return False
62
63     def can_edit_post(self, post):
64         return False
65
66     def can_wikify(self, post):
67         return False
68
69     def can_cancel_wiki(self, post):
70         return False
71
72     def can_retag_questions(self):
73         return False
74
75     def can_close_question(self, question):
76         return False
77
78     def can_reopen_question(self, question):
79         return False
80
81     def can_delete_post(self, post):
82         return False
83
84     def can_upload_files(self):
85         return False
86
87 def true_if_is_super_or_staff(fn):
88     def decorated(self, *args, **kwargs):
89         return self.is_superuser or self.is_staff or fn(self, *args, **kwargs)
90
91     return decorated
92
93 class User(BaseModel, DjangoUser):
94     is_approved = models.BooleanField(default=False)
95     email_isvalid = models.BooleanField(default=False)
96
97     reputation = models.PositiveIntegerField(default=0)
98     gold = models.PositiveIntegerField(default=0)
99     silver = models.PositiveIntegerField(default=0)
100     bronze = models.PositiveIntegerField(default=0)
101
102     last_seen = models.DateTimeField(default=datetime.datetime.now)
103     real_name = models.CharField(max_length=100, blank=True)
104     website = models.URLField(max_length=200, blank=True)
105     location = models.CharField(max_length=100, blank=True)
106     date_of_birth = models.DateField(null=True, blank=True)
107     about = models.TextField(blank=True)
108
109     subscriptions = models.ManyToManyField('Node', related_name='subscribers', through='QuestionSubscription')
110
111     vote_up_count = DenormalizedField("actions", canceled=False, action_type="voteup")
112     vote_down_count = DenormalizedField("actions", canceled=False, action_type="votedown")
113
114     def __unicode__(self):
115         return self.username
116
117     @property
118     def is_siteowner(self):
119         #temporary thing, for now lets just assume that the site owner will always be the first user of the application
120         return self.id == 1
121
122     @property
123     def gravatar(self):
124         return md5(self.email).hexdigest()
125
126     def save(self, *args, **kwargs):
127         if self.reputation < 0:
128             self.reputation = 0
129
130         new = not bool(self.id)
131
132         super(User, self).save(*args, **kwargs)
133
134         if new:
135             sub_settings = SubscriptionSettings(user=self)
136             sub_settings.save()
137
138     def get_absolute_url(self):
139         return self.get_profile_url()
140
141     def get_messages(self):
142         messages = []
143         for m in self.message_set.all():
144             messages.append(m.message)
145         return messages
146
147     def delete_messages(self):
148         self.message_set.all().delete()
149
150     @models.permalink
151     def get_profile_url(self):
152         return ('user_profile', (), {'id': self.id, 'slug': slugify(self.username)})
153
154     def get_absolute_url(self):
155         return self.get_profile_url()
156
157     def get_profile_link(self):
158         profile_link = u'<a href="%s">%s</a>' % (self.get_profile_url(), self.username)
159         return mark_safe(profile_link)
160
161     def get_visible_answers(self, question):
162         return question.answers.filter_state(deleted=False)
163
164     def get_vote_count_today(self):
165         today = datetime.date.today()
166         return self.actions.filter(canceled=False, action_type__in=("voteup", "votedown"),
167                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
168
169     def get_reputation_by_upvoted_today(self):
170         today = datetime.datetime.now()
171         sum = self.reputes.filter(reputed_at__range=(today - datetime.timedelta(days=1), today)).aggregate(
172                 models.Sum('value'))
173         #todo: redo this, maybe transform in the daily cap
174         #if sum.get('value__sum', None) is not None: return sum['value__sum']
175         return 0
176
177     def get_flagged_items_count_today(self):
178         today = datetime.date.today()
179         return self.actions.filter(canceled=False, action_type="flag",
180                                    action_date__gte=(today - datetime.timedelta(days=1))).count()
181
182     @true_if_is_super_or_staff
183     def can_view_deleted_post(self, post):
184         return post.author == self
185
186     @true_if_is_super_or_staff
187     def can_vote_up(self):
188         return self.reputation >= int(settings.REP_TO_VOTE_UP)
189
190     @true_if_is_super_or_staff
191     def can_vote_down(self):
192         return self.reputation >= int(settings.REP_TO_VOTE_DOWN)
193
194     def can_flag_offensive(self, post=None):
195         if post is not None and post.author == self:
196             return False
197         return self.is_superuser or self.is_staff or self.reputation >= int(settings.REP_TO_FLAG)
198
199     @true_if_is_super_or_staff
200     def can_view_offensive_flags(self, post=None):
201         if post is not None and post.author == self:
202             return True
203         return self.reputation >= int(settings.REP_TO_VIEW_FLAGS)
204
205     @true_if_is_super_or_staff
206     def can_comment(self, post):
207         return self == post.author or self.reputation >= int(settings.REP_TO_COMMENT
208                                                              ) or (post.__class__.__name__ == "Answer" and self == post.question.author)
209
210     @true_if_is_super_or_staff
211     def can_like_comment(self, comment):
212         return self != comment.author and (self.reputation >= int(settings.REP_TO_LIKE_COMMENT))
213
214     @true_if_is_super_or_staff
215     def can_edit_comment(self, comment):
216         return (comment.author == self and comment.added_at >= datetime.datetime.now() - datetime.timedelta(minutes=60)
217         ) or self.is_superuser
218
219     @true_if_is_super_or_staff
220     def can_delete_comment(self, comment):
221         return self == comment.author or self.reputation >= int(settings.REP_TO_DELETE_COMMENTS)
222
223     def can_convert_to_comment(self, answer):
224         return (not answer.marked) and (self.is_superuser or self.is_staff or answer.author == self or self.reputation >= int
225                 (settings.REP_TO_CONVERT_TO_COMMENT))
226
227     @true_if_is_super_or_staff
228     def can_accept_answer(self, answer):
229         return self == answer.question.author
230
231     @true_if_is_super_or_staff
232     def can_create_tags(self):
233         return self.reputation >= int(settings.REP_TO_CREATE_TAGS)
234
235     @true_if_is_super_or_staff
236     def can_edit_post(self, post):
237         return self == post.author or self.reputation >= int(settings.REP_TO_EDIT_OTHERS
238                                                              ) or (post.nis.wiki and self.reputation >= int(
239                 settings.REP_TO_EDIT_WIKI))
240
241     @true_if_is_super_or_staff
242     def can_wikify(self, post):
243         return self == post.author or self.reputation >= int(settings.REP_TO_WIKIFY)
244
245     @true_if_is_super_or_staff
246     def can_cancel_wiki(self, post):
247         return self == post.author
248
249     @true_if_is_super_or_staff
250     def can_retag_questions(self):
251         return self.reputation >= int(settings.REP_TO_RETAG)
252
253     @true_if_is_super_or_staff
254     def can_close_question(self, question):
255         return (self == question.author and self.reputation >= int(settings.REP_TO_CLOSE_OWN)
256         ) or self.reputation >= int(settings.REP_TO_CLOSE_OTHERS)
257
258     @true_if_is_super_or_staff
259     def can_reopen_question(self, question):
260         return self == question.author and self.reputation >= settings.REP_TO_REOPEN_OWN
261
262     @true_if_is_super_or_staff
263     def can_delete_post(self, post):
264         if post.node_type == "comment":
265             return self.can_delete_comment(post)
266
267         return (self == post.author and (post.__class__.__name__ == "Answer" or
268         not post.answers.exclude(author=self).count()))
269
270     @true_if_is_super_or_staff
271     def can_upload_files(self):
272         return self.reputation >= int(settings.REP_TO_UPLOAD)
273
274     def check_password(self, old_passwd):
275         self.__dict__.update(self.__class__.objects.filter(id=self.id).values('password')[0])
276         return DjangoUser.check_password(self, old_passwd)
277
278     @property
279     def suspension(self):
280         if self.__dict__.get('_suspension_dencache_', False) != None:
281             try:
282                 self.__dict__['_suspension_dencache_'] = self.actions.get(action_type="suspend", canceled=False)
283             except ObjectDoesNotExist:
284                 self.__dict__['_suspension_dencache_'] = None
285             except MultipleObjectsReturned:
286                 logging.error("Multiple suspension actions found for user %s (%s)" % (self.username, self.id))
287                 self.__dict__['_suspension_dencache_'] = self.actions.filter(action_type="suspend", canceled=False
288                                                                              ).order_by('-action_date')[0]
289
290         return self.__dict__['_suspension_dencache_']
291
292     def _pop_suspension_cache(self):
293         self.__dict__.pop('_suspension_dencache_', None)
294
295     def is_suspended(self):
296         if not self.is_active:
297             suspension = self.suspension
298
299             if suspension and suspension.extra.get('bantype', None) == 'forxdays' and (
300             datetime.datetime.now() > suspension.action_date + datetime.timedelta(
301                     days=int(suspension.extra.get('forxdays', 365)))):
302                 suspension.cancel()
303             else:
304                 return True
305
306         return False
307
308     class Meta:
309         app_label = 'forum'
310
311 class SubscriptionSettings(models.Model):
312     user = models.OneToOneField(User, related_name='subscription_settings')
313
314     enable_notifications = models.BooleanField(default=True)
315
316     #notify if
317     member_joins = models.CharField(max_length=1, default='n')
318     new_question = models.CharField(max_length=1, default='d')
319     new_question_watched_tags = models.CharField(max_length=1, default='i')
320     subscribed_questions = models.CharField(max_length=1, default='i')
321
322     #auto_subscribe_to
323     all_questions = models.BooleanField(default=False)
324     all_questions_watched_tags = models.BooleanField(default=False)
325     questions_asked = models.BooleanField(default=True)
326     questions_answered = models.BooleanField(default=True)
327     questions_commented = models.BooleanField(default=False)
328     questions_viewed = models.BooleanField(default=False)
329
330     #notify activity on subscribed
331     notify_answers = models.BooleanField(default=True)
332     notify_reply_to_comments = models.BooleanField(default=True)
333     notify_comments_own_post = models.BooleanField(default=True)
334     notify_comments = models.BooleanField(default=False)
335     notify_accepted = models.BooleanField(default=False)
336
337     class Meta:
338         app_label = 'forum'
339
340 from forum.utils.time import one_day_from_now
341
342 class ValidationHashManager(models.Manager):
343     def _generate_md5_hash(self, user, type, hash_data, seed):
344         return md5("%s%s%s%s" % (seed, "".join(map(str, hash_data)), user.id, type)).hexdigest()
345
346     def create_new(self, user, type, hash_data=[], expiration=None):
347         seed = ''.join(Random().sample(string.letters+string.digits, 12))
348         hash = self._generate_md5_hash(user, type, hash_data, seed)
349
350         obj = ValidationHash(hash_code=hash, seed=seed, user=user, type=type)
351
352         if expiration is not None:
353             obj.expiration = expiration
354
355         try:
356             obj.save()
357         except:
358             return None
359
360         return obj
361
362     def validate(self, hash, user, type, hash_data=[]):
363         try:
364             obj = self.get(hash_code=hash)
365         except:
366             return False
367
368         if obj.type != type:
369             return False
370
371         if obj.user != user:
372             return False
373
374         valid = (obj.hash_code == self._generate_md5_hash(obj.user, type, hash_data, obj.seed))
375
376         if valid:
377             if obj.expiration < datetime.datetime.now():
378                 obj.delete()
379                 return False
380             else:
381                 obj.delete()
382                 return True
383
384         return False
385
386 class ValidationHash(models.Model):
387     hash_code = models.CharField(max_length=255, unique=True)
388     seed = models.CharField(max_length=12)
389     expiration = models.DateTimeField(default=one_day_from_now)
390     type = models.CharField(max_length=12)
391     user = models.ForeignKey(User)
392
393     objects = ValidationHashManager()
394
395     class Meta:
396         unique_together = ('user', 'type')
397         app_label = 'forum'
398
399     def __str__(self):
400         return self.hash_code
401
402 class AuthKeyUserAssociation(models.Model):
403     key = models.CharField(max_length=255, null=False, unique=True)
404     provider = models.CharField(max_length=64)
405     user = models.ForeignKey(User, related_name="auth_keys")
406     added_at = models.DateTimeField(default=datetime.datetime.now)
407
408     class Meta:
409         app_label = 'forum'