forked from OSQA/osqa
/
post.py
2635 lines (2268 loc) · 98.1 KB
/
post.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import defaultdict
import datetime
import operator
import logging
from django.contrib.sitemaps import ping_google
from django.utils import html
from django.conf import settings as django_settings
from django.contrib.auth.models import User
from django.core import urlresolvers
from django.db import models, transaction
from django.utils import html as html_utils
from django.utils.text import truncate_html_words
from django.utils.translation import activate as activate_language
from django.utils.translation import get_language
from django.utils.translation import ugettext as _
from django.utils.http import urlquote as django_urlquote
from django.core import exceptions as django_exceptions
from django.core import cache
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.contrib.contenttypes.models import ContentType
import askbot
from askbot import signals
from askbot.utils.loading import load_module, load_plugin
from askbot.utils.slug import slugify
from askbot import const
from askbot.models.tag import Tag, MarkedTag
from askbot.models.tag import tags_match_some_wildcard
from askbot.conf import settings as askbot_settings
from askbot import exceptions
from askbot.utils import markup
from askbot.utils.html import (get_word_count, has_moderated_tags,
moderate_tags, sanitize_html, strip_tags, site_url)
from askbot.models.base import BaseQuerySetManager, DraftContent
#todo: maybe merge askbot.utils.markup and forum.utils.html
from askbot.utils.diff import textDiff as htmldiff
from askbot.search import mysql
def default_html_moderator(post):
"""Moderates inline HTML items: images and/or links
depending on what items are moderated per settings.
Returns sanitized html with suspicious
content edited out and replaced with warning signs.
Moderators content is not sanitized.
Latest revision is placed on the moderation queue.
TODO: Make moderation work per-item: e.g. per link
or per image.
This function can be overridden by setting python path
to the alternative function as a value of `ASKBOT_HTML_MODERATOR`
in the settings.py, e.g:
ASKBOT_HTML_MODERATOR = 'my_extension.html_moderator'
"""
if not (askbot_settings.MODERATE_LINKS or askbot_settings.MODERATE_IMAGES):
return post.html
rev = post.current_revision
author = rev.author
not_admin = not author.is_administrator_or_moderator()
if not_admin and has_moderated_tags(post.html):
before = post.html
after = moderate_tags(before)
if after != before:
rev.place_on_moderation_queue()
return after
return post.html
class PostToGroup(models.Model):
post = models.ForeignKey('Post')
group = models.ForeignKey('Group')
class Meta:
unique_together = ('post', 'group')
app_label = 'askbot'
db_table = 'askbot_post_groups'
class PostQuerySet(models.query.QuerySet):
"""
Custom query set subclass for :class:`~askbot.models.Post`
"""
#todo: we may not need this query set class,
#as all methods on this class seem to want to
#belong to Thread manager or Query set.
def get_for_user(self, user):
from askbot.models.user import Group
if askbot_settings.GROUPS_ENABLED:
if user is None or user.is_anonymous():
groups = [Group.objects.get_global_group()]
else:
groups = user.get_groups()
return self.filter(groups__in = groups).distinct()
else:
return self
def get_by_text_query(self, search_query):
"""returns a query set of questions,
matching the full text query
"""
return self.filter(
models.Q(thread__title__icontains = search_query)\
| models.Q(text__icontains = search_query)\
| models.Q(thread__tagnames = search_query)\
| models.Q(thread__posts__text__icontains = search_query, thread__posts__post_type='answer')
)
# #todo - goes to thread - we search whole threads
# if getattr(django_settings, 'USE_SPHINX_SEARCH', False):
# matching_questions = Question.sphinx_search.query(search_query)
# question_ids = [q.id for q in matching_questions]
# return Question.objects.filter(deleted = False, id__in = question_ids)
# if django_settings.DATABASE_ENGINE == 'mysql' and mysql.supports_full_text_search():
# return self.filter(
# models.Q(thread__title__search = search_query)\
# | models.Q(text__search = search_query)\
# | models.Q(thread__tagnames__search = search_query)\
# | models.Q(answers__text__search = search_query)
# )
# elif 'postgresql_psycopg2' in askbot.get_database_engine_name():
# rank_clause = "ts_rank(question.text_search_vector, plainto_tsquery(%s))";
# search_query = '&'.join(search_query.split())
# extra_params = (search_query,)
# extra_kwargs = {
# 'select': {'relevance': rank_clause},
# 'where': ['text_search_vector @@ plainto_tsquery(%s)'],
# 'params': extra_params,
# 'select_params': extra_params,
# }
# return self.extra(**extra_kwargs)
# else:
# #fallback to dumb title match search
# return self.filter(thread__title__icontains=search_query)
def added_between(self, start, end):
"""questions added between ``start`` and ``end`` timestamps"""
#todo: goes to thread
return self.filter(
added_at__gt = start
).exclude(
added_at__gt = end
)
def get_questions_needing_reminder(self,
user = None,
activity_type = None,
recurrence_delay = None):
"""returns list of questions that need a reminder,
corresponding the given ``activity_type``
``user`` - is the user receiving the reminder
``recurrence_delay`` - interval between sending the
reminders about the same question
"""
#todo: goes to thread
from askbot.models import Activity#avoid circular import
question_list = list()
for question in self:
try:
activity = Activity.objects.get(
user = user,
question = question,
activity_type = activity_type
)
now = datetime.datetime.now()
if now < activity.active_at + recurrence_delay:
continue
except Activity.DoesNotExist:
activity = Activity(
user = user,
question = question,
activity_type = activity_type,
content_object = question,
)
activity.active_at = datetime.datetime.now()
activity.save()
question_list.append(question)
return question_list
def get_author_list(self, **kwargs):
#todo: - this is duplication - answer manager also has this method
#will be gone when models are consolidated
#note that method get_question_and_answer_contributors is similar in function
#todo: goes to thread
authors = set()
for question in self:
authors.update(question.get_author_list(**kwargs))
return list(authors)
class PostManager(BaseQuerySetManager):
def get_query_set(self):
return PostQuerySet(self.model)
def get_questions(self, user=None):
questions = self.filter(post_type='question')
return questions.get_for_user(user)
def get_answers(self, user=None):
"""returns query set of answer posts,
optionally filtered to exclude posts of groups
to which user does not belong"""
answers = self.filter(post_type='answer')
return answers.get_for_user(user)
def get_comments(self):
return self.filter(post_type='comment')
def create_new_tag_wiki(self, text = None, author = None):
return self.create_new(
None,#this post type is threadless
author,
datetime.datetime.now(),
text,
wiki = True,
post_type = 'tag_wiki'
)
def create_new(
self,
thread,
author,
added_at,
text,
parent=None,
wiki=False,
is_private=False,
email_notify=False,
post_type=None,
by_email=False,
ip_addr=None
):
# TODO: Some of this code will go to Post.objects.create_new
assert(post_type in const.POST_TYPES)
if thread:
language_code = thread.language_code
else:
language_code = get_language()
post = Post(
post_type=post_type,
thread=thread,
parent=parent,
author=author,
added_at=added_at,
wiki=wiki,
text=text,
language_code=language_code
#.html field is denormalized by the save() call
)
if post.wiki:
post.last_edited_by = post.author
post.last_edited_at = added_at
post.wikified_at = added_at
#possibly modify the is_private, if one of the groups
#mandates explicit publishing of the posts
is_private = is_private or \
(thread and thread.requires_response_moderation(author))
post.save() #saved so that revision can have post_id
revision = post.add_revision(
author=author,
revised_at=added_at,
text=text,
comment=unicode(const.POST_STATUS['default_version']),
by_email=by_email,
ip_addr=ip_addr
)
#now we parse html
parse_results = post.parse_and_save(author=author, is_private=is_private)
#moderate inline content
post.moderate_html()
if revision.revision > 0:
signals.post_updated.send(
post=post,
updated_by=author,
newly_mentioned_users=parse_results['newly_mentioned_users'],
timestamp=added_at,
created=True,
diff=parse_results['diff'],
sender=post.__class__
)
return post
#todo: instead of this, have Thread.add_answer()
def create_new_answer(
self,
thread,
author,
added_at,
text,
wiki=False,
is_private=False,
email_notify=False,
by_email=False,
ip_addr=None,
):
answer = self.create_new(
thread,
author,
added_at,
text,
wiki=wiki,
is_private=is_private,
post_type='answer',
by_email=by_email,
ip_addr=ip_addr
)
#set notification/delete
if email_notify:
thread.followed_by.add(author)
else:
thread.followed_by.remove(author)
#update thread data
#todo: this totally belongs to some `Thread` class method
if answer.is_approved():
thread.answer_count += 1
thread.save()
thread.set_last_activity_info(
last_activity_at=added_at,
last_activity_by=author
) # this should be here because it regenerates cached thread summary html
return answer
def precache_comments(self, for_posts, visitor):
"""
Fetches comments for given posts, and stores them in post._cached_comments
Additionally, annotates posts with ``upvoted_by_user`` parameter, if visitor is logged in
"""
qs = Post.objects.get_comments().filter(parent__in=for_posts).select_related('author')
comments_reversed = askbot_settings.COMMENTS_REVERSED
if visitor.is_anonymous():
if comments_reversed:
comments = list(qs.order_by('-added_at'))
else:
comments = list(qs.order_by('added_at'))
else:
upvoted_by_user = list(qs.filter(votes__user=visitor).distinct())
not_upvoted_by_user = list(qs.exclude(votes__user=visitor).distinct())
for c in upvoted_by_user:
c.upvoted_by_user = 1 # numeric value to maintain compatibility with previous version of this code
comments = upvoted_by_user + not_upvoted_by_user
comments.sort(key=operator.attrgetter('added_at'), reverse=comments_reversed)
post_map = defaultdict(list)
for cm in comments:
post_map[cm.parent_id].append(cm)
for post in for_posts:
post.set_cached_comments(post_map[post.id])
# Old Post.get_comment(self, visitor=None) method:
# if visitor.is_anonymous():
# return self.comments.order_by('added_at')
# else:
# upvoted_by_user = list(self.comments.filter(votes__user=visitor).distinct())
# not_upvoted_by_user = list(self.comments.exclude(votes__user=visitor).distinct())
#
# for c in upvoted_by_user:
# c.upvoted_by_user = 1 # numeric value to maintain compatibility with previous version of this code
#
# comments = upvoted_by_user + not_upvoted_by_user
# comments.sort(key=operator.attrgetter('added_at'))
#
# return comments
class MockPost(object):
"""Used for special purposes, e.g. to fill
out the js templates for the posts made via ajax
"""
def __init__(self, post_type=None, author=None):
from askbot.models.user import MockUser
self.post_type = post_type
self.score = 0
self.id = 0
self.author = MockUser()
self.summary = ''
self.added_at = datetime.datetime.now()
def needs_moderation(self):
return False
POST_RENDERERS_MAP = getattr(django_settings, 'ASKBOT_POST_RENDERERS', {
'plain-text': 'askbot.utils.markup.plain_text_input_converter',
'markdown': 'askbot.utils.markup.markdown_input_converter',
'tinymce': 'askbot.utils.markup.tinymce_input_converter',
})
def get_post_renderer_type(post_type):
have_simple_comment = (
post_type == 'comment' and
askbot_settings.COMMENTS_EDITOR_TYPE == 'plain-text'
)
if have_simple_comment:
return 'plain-text'
else:
return askbot_settings.EDITOR_TYPE
class Post(models.Model):
post_type = models.CharField(max_length=255, db_index=True)
#NOTE!!! if these fields are deleted - then jive import needs fixing!!!
old_question_id = models.PositiveIntegerField(null=True, blank=True, default=None, unique=True)
old_answer_id = models.PositiveIntegerField(null=True, blank=True, default=None, unique=True)
old_comment_id = models.PositiveIntegerField(null=True, blank=True, default=None, unique=True)
parent = models.ForeignKey('Post', blank=True, null=True, related_name='comments') # Answer or Question for Comment
thread = models.ForeignKey('Thread', blank=True, null=True, default=None, related_name='posts')
current_revision = models.ForeignKey(
'PostRevision',
blank=True,
null=True, #nullable b/c we have to first save post
#and then add link to current revision
#(which has a non-nullable fk to post)
related_name='rendered_posts'
)# "rendered" revision
groups = models.ManyToManyField('Group', through='PostToGroup', related_name = 'group_posts')#used for group-private posts
author = models.ForeignKey(User, related_name='posts')
added_at = models.DateTimeField(default=datetime.datetime.now)
#endorsed == accepted as best in the case of answer
#use word 'endorsed' to differentiate from 'approved', which
#is used for the moderation
#note: accepted answer is also denormalized on the Thread model
endorsed = models.BooleanField(default=False, db_index=True)
endorsed_by = models.ForeignKey(User, null=True, blank=True, related_name='endorsed_posts')
endorsed_at = models.DateTimeField(null=True, blank=True)
#denormalized data: the core approval of the posts is made
#in the revisions. In the revisions there is more data about
#approvals - by whom and when
approved = models.BooleanField(default=True, db_index=True)
deleted = models.BooleanField(default=False, db_index=True)
deleted_at = models.DateTimeField(null=True, blank=True)
deleted_by = models.ForeignKey(User, null=True, blank=True, related_name='deleted_posts')
wiki = models.BooleanField(default=False)
wikified_at = models.DateTimeField(null=True, blank=True)
locked = models.BooleanField(default=False)
locked_by = models.ForeignKey(User, null=True, blank=True, related_name='locked_posts')
locked_at = models.DateTimeField(null=True, blank=True)
points = models.IntegerField(default=0, db_column='score')
vote_up_count = models.IntegerField(default=0)
vote_down_count = models.IntegerField(default=0)
comment_count = models.PositiveIntegerField(default=0)
offensive_flag_count = models.SmallIntegerField(default=0)
last_edited_at = models.DateTimeField(null=True, blank=True)
last_edited_by = models.ForeignKey(User, null=True, blank=True, related_name='last_edited_posts')
html = models.TextField(null=True)#html rendition of the latest revision
text = models.TextField(null=True)#denormalized copy of latest revision
language_code = models.CharField(
choices=django_settings.LANGUAGES,
default=django_settings.LANGUAGE_CODE,
max_length=16,
)
# Denormalised data
summary = models.TextField(null=True)
#note: anonymity here applies to question only, but
#the field will still go to thread
#maybe we should rename it to is_question_anonymous
#we might have to duplicate the is_anonymous on the Post,
#if we are to allow anonymous answers
#the reason is that the title and tags belong to thread,
#but the question body to Post
is_anonymous = models.BooleanField(default=False)
objects = PostManager()
class Meta:
app_label = 'askbot'
db_table = 'askbot_post'
#property to support legacy themes in case there are.
@property
def score(self):
return int(self.points)
@score.setter
def score(self, number):
if number:
self.points = int(number)
def as_tweet(self):
"""a naive tweet representation of post
todo: add mentions to relevant people
"""
url = site_url(self.get_absolute_url(no_slug=True))
if self.post_type == 'question':
tweet = askbot_settings.WORDS_QUESTION_SINGULAR + ': '
elif self.post_type == 'answer':
tweet = askbot_settings.WORDS_ANSWER_SINGULAR + ': '
chars_left = 140 - (len(url) + len(tweet) + 1)
title_str = self.thread.title[:chars_left]
return tweet + title_str + ' ' + url
def parse_post_text(self):
"""typically post has a field to store raw source text
in comment it is called .comment, in Question and Answer it is
called .text
also there is another field called .html (consistent across models)
so the goal of this function is to render raw text into .html
and extract any metadata given stored in source (currently
this metadata is limited by twitter style @mentions
but there may be more in the future
function returns a dictionary with the following keys
html
newly_mentioned_users - list of <User> objects
removed_mentions - list of mention <Activity> objects - for removed ones
"""
text_converter = self.get_text_converter()
text = text_converter(self.text)
#todo, add markdown parser call conditional on
#self.use_markdown flag
post_html = text
mentioned_authors = list()
removed_mentions = list()
if '@' in text:
op = self.get_origin_post()
if op.id:
anticipated_authors = op.get_author_list(
include_comments = True,
recursive = True
)
else:
anticipated_authors = list()
extra_name_seeds = markup.extract_mentioned_name_seeds(text)
extra_authors = set()
for name_seed in extra_name_seeds:
extra_authors.update(
User.objects.filter(username__istartswith = name_seed)
)
#it is important to preserve order here so that authors of post
#get mentioned first
anticipated_authors += list(extra_authors)
mentioned_authors, post_html = markup.mentionize_text(
text,
anticipated_authors
)
#todo: stuff below possibly does not belong here
#find mentions that were removed and identify any previously
#entered mentions so that we can send alerts on only new ones
from askbot.models.user import Activity
if self.pk is not None:
#only look for previous mentions if post was already saved before
prev_mention_qs = Activity.objects.get_mentions(
mentioned_in = self
)
new_set = set(mentioned_authors)
for prev_mention in prev_mention_qs:
user = prev_mention.get_mentioned_user()
if user is None:
continue
if user in new_set:
#don't report mention twice
new_set.remove(user)
else:
removed_mentions.append(prev_mention)
mentioned_authors = list(new_set)
data = {
'html': post_html,
'newly_mentioned_users': mentioned_authors,
'removed_mentions': removed_mentions,
}
return data
#todo: when models are merged, it would be great to remove author parameter
def parse_and_save(self, author=None, **kwargs):
"""converts .text version of post to .html
using appropriate converter.
@mentions are rendered as well as internal links.
"""
assert(author is not None)
last_revision = self.html
data = self.parse_post_text()
#todo: possibly remove feature of posting links
#depending on user's reputation
self.html = author.fix_html_links(data['html'])
#a hack allowing to save denormalized .summary field for questions
if hasattr(self, 'summary'):
self.summary = self.get_snippet()
newly_mentioned_users = set(data['newly_mentioned_users']) - set([author])
removed_mentions = data['removed_mentions']
#delete removed mentions
for rm in removed_mentions:
rm.delete()
created = self.pk is None
is_private = kwargs.pop('is_private', False)
group_id = kwargs.pop('group_id', None)
#this save must precede saving the mention activity
#as well as assigning groups to the post
#because generic relation needs primary key of the related object
super(self.__class__, self).save(**kwargs)
#todo: move this group stuff out of this function
if self.is_comment():
#copy groups from the parent post into the comment
groups = self.parent.groups.all()
self.add_to_groups(groups)
elif is_private or group_id:
self.make_private(author, group_id = group_id)
elif self.thread_id:#is connected to thread
#inherit privacy scope from thread
thread_groups = self.thread.groups.all()
self.add_to_groups(thread_groups)
else:
self.make_public()
if last_revision:
diff = htmldiff(
sanitize_html(last_revision),
sanitize_html(self.html)
)
else:
diff = sanitize_html(self.get_snippet())
timestamp = self.get_time_of_last_edit()
try:
from askbot.conf import settings as askbot_settings
if askbot_settings.GOOGLE_SITEMAP_CODE != '':
ping_google()
except Exception:
logging.debug('cannot ping google - did you register with them?')
return {'diff': diff, 'newly_mentioned_users': newly_mentioned_users}
def is_question(self):
return self.post_type == 'question'
def is_answer(self):
return self.post_type == 'answer'
def is_comment(self):
return self.post_type == 'comment'
def is_qa_content(self):
return self.post_type in ('question', 'answer', 'comment')
def is_tag_wiki(self):
return self.post_type == 'tag_wiki'
def is_reject_reason(self):
return self.post_type == 'reject_reason'
def get_last_edited_date(self):
"""returns date of last edit or date of creation
if there were no edits"""
return self.last_edited_at or self.added_at
def get_moderators(self):
"""returns query set of users who are site administrators
and moderators"""
user_filter = models.Q(is_superuser=True) | models.Q(status='m')
if askbot_settings.GROUPS_ENABLED:
user_filter = user_filter & models.Q(groups__in=self.groups.all())
return User.objects.filter(user_filter).distinct()
def get_previous_answer(self, user=None):
"""returns a previous answer to a given answer;
only works on the "answer" post types"""
assert(self.post_type == 'answer')
all_answers = self.thread.get_answers(user=user)
matching_answers = all_answers.filter(
added_at__lt=self.added_at,
).order_by('-added_at')
if len(matching_answers) == 0:
return None
answer = matching_answers[0]
if answer.id == self.id:
return None
if answer.added_at > self.added_at:
return None
return answer
def get_text_converter(self):
"""returns text converter, which may
be overridden by setting
ASKBOT_POST_RENDERERS (look for format in the source code)
"""
renderer_type = get_post_renderer_type(self.post_type)
try:
renderer_path = POST_RENDERERS_MAP[renderer_type]
except KeyError:
raise NotImplementedError
return load_module(renderer_path)
def has_group(self, group):
"""true if post belongs to the group"""
return self.groups.filter(id=group.id).exists()
def add_to_groups(self, groups):
"""associates post with groups"""
#this is likely to be temporary - we add
#vip groups to the list behind the scenes.
groups = list(groups)
#add moderator groups to the post implicitly
from askbot.models.user import Group
vips = Group.objects.filter(is_vip=True)
groups.extend(vips)
#todo: use bulk-creation
for group in groups:
PostToGroup.objects.get_or_create(post=self, group=group)
if self.is_answer() or self.is_question():
comments = self.comments.all()
for group in groups:
for comment in comments:
PostToGroup.objects.get_or_create(post=comment, group=group)
def remove_from_groups(self, groups):
PostToGroup.objects.filter(post=self, group__in=groups).delete()
if self.is_answer() or self.is_question():
comment_ids = self.comments.all().values_list('id', flat=True)
PostToGroup.objects.filter(
post__id__in=comment_ids,
group__in=groups
).delete()
@transaction.commit_manually
def issue_update_notifications(
self,
updated_by=None,
notify_sets=None,
activity_type=None,
suppress_email=False,
timestamp=None,
diff=None
):
"""Called when a post is updated. Arguments:
* ``notify_sets`` - result of ``Post.get_notify_sets()`` method
The method does two things:
* records "red envelope" recipients of the post
* sends email alerts to all subscribers to the post
"""
assert(activity_type is not None)
if diff:
summary = diff
else:
summary = self.get_snippet()
from askbot.models import Activity
update_activity = Activity(
user = updated_by,
active_at = timestamp,
content_object = self,
activity_type = activity_type,
question = self.get_origin_post(),
summary = summary
)
update_activity.save()
update_activity.add_recipients(notify_sets['for_inbox'])
#create new mentions (barring the double-adds)
from askbot.models import Activity
for u in notify_sets['for_mentions'] - notify_sets['for_inbox']:
Activity.objects.create_new_mention(
mentioned_whom = u,
mentioned_in = self,
mentioned_by = updated_by,
mentioned_at = timestamp
)
for user in (notify_sets['for_inbox'] | notify_sets['for_mentions']):
user.update_response_counts()
#shortcircuit if the email alerts are disabled
if suppress_email == True or askbot_settings.ENABLE_EMAIL_ALERTS == False:
return
#todo: fix this temporary spam protection plug
if askbot_settings.MIN_REP_TO_TRIGGER_EMAIL:
if not (updated_by.is_administrator() or updated_by.is_moderator()):
if updated_by.reputation < askbot_settings.MIN_REP_TO_TRIGGER_EMAIL:
notify_sets['for_email'] = \
[u for u in notify_sets['for_email'] if u.is_administrator()]
if not django_settings.CELERY_ALWAYS_EAGER:
cache_key = 'instant-notification-%d-%d' % (self.thread.id, updated_by.id)
if cache.cache.get(cache_key):
return
cache.cache.set(cache_key, True, django_settings.NOTIFICATION_DELAY_TIME)
from askbot.tasks import send_instant_notifications_about_activity_in_post
transaction.commit()
send_instant_notifications_about_activity_in_post.apply_async((
update_activity.pk,
self.id,
notify_sets['for_email']),
countdown=django_settings.NOTIFICATION_DELAY_TIME
)
transaction.commit()
def make_private(self, user, group_id=None):
"""makes post private within user's groups
todo: this is a copy-paste in thread and post
"""
from askbot.models.user import Group
if group_id:
group = Group.objects.get(id=group_id)
groups = [group]
self.add_to_groups(groups)
global_group = Group.objects.get_global_group()
if group != global_group:
self.remove_from_groups((global_group,))
else:
if self.thread_id and self.is_question() is False:
#for thread-related responses we base
#privacy scope on thread + add a personal group
personal_group = user.get_personal_group()
thread_groups = self.thread.get_groups_shared_with()
groups = set([personal_group]) | set(thread_groups)
else:
groups = user.get_groups(private=True)
self.add_to_groups(groups)
self.remove_from_groups((Group.objects.get_global_group(),))
if len(groups) == 0:
message = _('Sharing did not work, because group is unknown')
user.message_set.create(message=message)
def make_public(self):
"""removes the privacy mark from users groups"""
from askbot.models.user import Group
groups = (Group.objects.get_global_group(),)
self.add_to_groups(groups)
def merge_post(self, post):
"""merge with other post"""
#take latest revision of current post R1
rev = self.get_latest_revision()
orig_text = rev.text
for rev in post.revisions.all().order_by('revision'):
#for each revision of other post Ri
#append content of Ri to R1 and use author
new_text = orig_text + '\n\n' + rev.text
author = rev.author
self.apply_edit(
edited_by=rev.author,
text=new_text,
comment=_('merged revision'),
by_email=False,
edit_anonymously=rev.is_anonymous,
suppress_email=True,
ip_addr=rev.ip_addr
)
if post.is_question() or post.is_answer():
comments = Post.objects.get_comments().filter(parent=post)
comments.update(parent=self)
#todo: implement redirects
if post.is_question():
self.old_question_id = post.id
elif post.is_answer():
self.old_answer_id = post.id
elif post.is_comment():
self.old_comment_id = post.id
self.save()
post.delete()
def moderate_html(self):
"""moderate inline content, such
as links and images"""
moderate = load_plugin(
'ASKBOT_HTML_MODERATOR',
'askbot.models.post.default_html_moderator'
)
before = self.html
after = moderate(self)
if after != before:
self.html = after
self.summary = self.get_snippet()
self.save()
def is_private(self):
"""true, if post belongs to the global group"""
if askbot_settings.GROUPS_ENABLED:
from askbot.models.user import Group
group = Group.objects.get_global_group()
return not self.groups.filter(id=group.id).exists()
return False
def set_runtime_needs_moderation(self):
"""Used at runtime only, the value is not
stored in the database"""
self._is_approved = False
def set_is_approved(self, is_approved):
"""sets denormalized value of whether post/thread is
approved"""
self.approved = is_approved
self.save()
if self.is_question():
self.thread.approved = is_approved
self.thread.save()
def is_approved(self):
"""``False`` only when moderation is ``True`` and post
``self.approved is False``
"""
if getattr(self, '_is_approved', True) == False:
return False
if askbot_settings.CONTENT_MODERATION_MODE == 'premoderation':
if self.approved:
return True
if self.revisions.filter(revision=0).count() == 1:
return False
return True
def needs_moderation(self):
#todo: do we need this, can't we just use is_approved()?
return self.is_approved() is False
def get_absolute_url(self,
no_slug=False,
question_post=None,
language=None,
thread=None
):
from askbot.utils.slug import slugify
#todo: the url generation function is pretty bad -
#the trailing slash is entered in three places here + in urls.py
if not hasattr(self, '_thread_cache') and thread:
self._thread_cache = thread
is_multilingual = getattr(django_settings, 'ASKBOT_MULTILINGUAL', False)
if is_multilingual:
request_language = get_language()
activate_language(language or self.language_code)
if self.is_answer():