[IMP] better layout and options
[odoo/odoo.git] / addons / website_forum / models / forum.py
1 # -*- coding: utf-8 -*-
2
3 from datetime import datetime
4
5 import openerp
6 from openerp import tools
7 from openerp import SUPERUSER_ID
8 from openerp.addons.website.models.website import slug
9 from openerp.osv import osv, fields
10 from openerp.tools import html2plaintext
11 from openerp.tools.translate import _
12
13
14 class KarmaError(ValueError):
15     """ Karma-related error, used for forum and posts. """
16     pass
17
18
19 class Forum(osv.Model):
20     """TDE TODO: set karma values for actions dynamic for a given forum"""
21     _name = 'forum.forum'
22     _description = 'Forums'
23     _inherit = ['mail.thread', 'website.seo.metadata']
24
25     _columns = {
26         'name': fields.char('Forum Name', required=True, translate=True),
27         'faq': fields.html('Guidelines'),
28         'description': fields.html('Description'),
29         'introduction_message': fields.html('Introduction Message'),
30         'relevancy_option_first': fields.float('First Relevancy Parameter'),
31         'relevancy_option_second': fields.float('Second Relevancy Parameter'),
32         'default_order': fields.selection([
33             ('creation','Newest'),
34             ('date','Last Updated'),
35             ('vote','Most Voted'),
36             ('relevancy','Relevancy'),
37             ], 'Default Order', required=True),
38         'allow_link': fields.boolean('Links', help="When clicking on the post, it redirects to an external link"),
39         'allow_question': fields.boolean('Questions', help="Users can answer only once per question. Contributors can edit answers and mark the right ones."),
40         'allow_discussion': fields.boolean('Discussions'),
41         # karma generation
42         'karma_gen_question_new': fields.integer('Post a Questions'),
43         'karma_gen_question_upvote': fields.integer('Upvote a Question'),
44         'karma_gen_question_downvote': fields.integer('Downvote a Question'),
45         'karma_gen_answer_upvote': fields.integer('Upvote an Answer'),
46         'karma_gen_answer_downvote': fields.integer('Downvote an answer'),
47         'karma_gen_answer_accept': fields.integer('Accept an Answer'),
48         'karma_gen_answer_accepted': fields.integer('Have Your Answer Accepted'),
49         'karma_gen_answer_flagged': fields.integer('Have Your Answer Flagged'),
50         # karma-based actions
51         'karma_ask': fields.integer('Ask a new question'),
52         'karma_answer': fields.integer('Answer a question'),
53         'karma_edit_own': fields.integer('Edit its own posts'),
54         'karma_edit_all': fields.integer('Edit all posts'),
55         'karma_close_own': fields.integer('Close its own posts'),
56         'karma_close_all': fields.integer('Close all posts'),
57         'karma_unlink_own': fields.integer('Delete its own posts'),
58         'karma_unlink_all': fields.integer('Delete all posts'),
59         'karma_upvote': fields.integer('Upvote'),
60         'karma_downvote': fields.integer('Downvote'),
61         'karma_answer_accept_own': fields.integer('Accept an answer on its own questions'),
62         'karma_answer_accept_all': fields.integer('Accept an answers to all questions'),
63         'karma_editor_link_files': fields.integer('Linking files (Editor)'),
64         'karma_editor_clickable_link': fields.integer('Add clickable links (Editor)'),
65         'karma_comment_own': fields.integer('Comment its own posts'),
66         'karma_comment_all': fields.integer('Comment all posts'),
67         'karma_comment_convert_own': fields.integer('Convert its own answers to comments and vice versa'),
68         'karma_comment_convert_all': fields.integer('Convert all answers to answers and vice versa'),
69         'karma_comment_unlink_own': fields.integer('Unlink its own comments'),
70         'karma_comment_unlink_all': fields.integer('Unlink all comments'),
71         'karma_retag': fields.integer('Change question tags'),
72         'karma_flag': fields.integer('Flag a post as offensive'),
73     }
74
75     def _get_default_faq(self, cr, uid, context=None):
76         fname = openerp.modules.get_module_resource('website_forum', 'data', 'forum_default_faq.html')
77         with open(fname, 'r') as f:
78             return f.read()
79         return False
80
81     _defaults = {
82         'default_order': 'date',
83         'allow_question': True,
84         'allow_link': False,
85         'allow_discussion': False,
86         'description': 'This community is for professionals and enthusiasts of our products and services.',
87         'faq': _get_default_faq,
88         'introduction_message': """<h1>Welcome to Odoo Forum</h1>
89                   <p> This community is for professionals and enthusiasts of our products and services.
90                       Share and discuss the best content and new marketing ideas,
91                       build your professional profile and become a better marketer together.
92                   </p>""",
93         'relevancy_option_first': 0.8,
94         'relevancy_option_second': 1.8,
95         'karma_gen_question_new': 2,
96         'karma_gen_question_upvote': 5,
97         'karma_gen_question_downvote': -2,
98         'karma_gen_answer_upvote': 10,
99         'karma_gen_answer_downvote': -2,
100         'karma_gen_answer_accept': 2,
101         'karma_gen_answer_accepted': 15,
102         'karma_gen_answer_flagged': -100,
103         'karma_ask': 0,
104         'karma_answer': 0,
105         'karma_edit_own': 1,
106         'karma_edit_all': 300,
107         'karma_close_own': 100,
108         'karma_close_all': 500,
109         'karma_unlink_own': 500,
110         'karma_unlink_all': 1000,
111         'karma_upvote': 5,
112         'karma_downvote': 50,
113         'karma_answer_accept_own': 20,
114         'karma_answer_accept_all': 500,
115         'karma_editor_link_files': 20,
116         'karma_editor_clickable_link': 20,
117         'karma_comment_own': 1,
118         'karma_comment_all': 1,
119         'karma_comment_convert_own': 50,
120         'karma_comment_convert_all': 500,
121         'karma_comment_unlink_own': 50,
122         'karma_comment_unlink_all': 500,
123         'karma_retag': 75,
124         'karma_flag': 500,
125     }
126
127     def create(self, cr, uid, values, context=None):
128         if context is None:
129             context = {}
130         create_context = dict(context, mail_create_nolog=True)
131         return super(Forum, self).create(cr, uid, values, context=create_context)
132
133
134 class Post(osv.Model):
135     _name = 'forum.post'
136     _description = 'Forum Post'
137     _inherit = ['mail.thread', 'website.seo.metadata']
138     _order = "is_correct DESC, vote_count DESC, write_date DESC"
139
140     def _get_post_relevancy(self, cr, uid, ids, field_name, arg, context):
141         res = dict.fromkeys(ids, 0)
142         for post in self.browse(cr, uid, ids, context=context):
143             days = (datetime.today() - datetime.strptime(post.create_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)).days
144             relavency = abs(post.vote_count - 1) ** post.forum_id.relevancy_option_first / ( days + 2) ** post.forum_id.relevancy_option_second
145             res[post.id] = relavency if (post.vote_count - 1) >= 0 else -relavency
146         return res
147
148     def _get_user_vote(self, cr, uid, ids, field_name, arg, context):
149         res = dict.fromkeys(ids, 0)
150         vote_ids = self.pool['forum.post.vote'].search(cr, uid, [('post_id', 'in', ids), ('user_id', '=', uid)], context=context)
151         for vote in self.pool['forum.post.vote'].browse(cr, uid, vote_ids, context=context):
152             res[vote.post_id.id] = vote.vote
153         return res
154
155     def _get_vote_count(self, cr, uid, ids, field_name, arg, context):
156         res = dict.fromkeys(ids, 0)
157         for post in self.browse(cr, uid, ids, context=context):
158             for vote in post.vote_ids:
159                 res[post.id] += int(vote.vote)
160         return res
161
162     def _get_post_from_vote(self, cr, uid, ids, context=None):
163         result = {}
164         for vote in self.pool['forum.post.vote'].browse(cr, uid, ids, context=context):
165             result[vote.post_id.id] = True
166         return result.keys()
167
168     def _get_user_favourite(self, cr, uid, ids, field_name, arg, context):
169         res = dict.fromkeys(ids, False)
170         for post in self.browse(cr, uid, ids, context=context):
171             if uid in [f.id for f in post.favourite_ids]:
172                 res[post.id] = True
173         return res
174
175     def _get_favorite_count(self, cr, uid, ids, field_name, arg, context):
176         res = dict.fromkeys(ids, 0)
177         for post in self.browse(cr, uid, ids, context=context):
178             res[post.id] += len(post.favourite_ids)
179         return res
180
181     def _get_post_from_hierarchy(self, cr, uid, ids, context=None):
182         post_ids = set(ids)
183         for post in self.browse(cr, SUPERUSER_ID, ids, context=context):
184             if post.parent_id:
185                 post_ids.add(post.parent_id.id)
186         return list(post_ids)
187
188     def _get_child_count(self, cr, uid, ids, field_name=False, arg={}, context=None):
189         res = dict.fromkeys(ids, 0)
190         for post in self.browse(cr, uid, ids, context=context):
191             if post.parent_id:
192                 res[post.parent_id.id] = len(post.parent_id.child_ids)
193             else:
194                 res[post.id] = len(post.child_ids)
195         return res
196
197     def _get_uid_answered(self, cr, uid, ids, field_name, arg, context=None):
198         res = dict.fromkeys(ids, False)
199         for post in self.browse(cr, uid, ids, context=context):
200             res[post.id] = any(answer.create_uid.id == uid for answer in post.child_ids)
201         return res
202
203     def _get_has_validated_answer(self, cr, uid, ids, field_name, arg, context=None):
204         res = dict.fromkeys(ids, False)
205         ans_ids = self.search(cr, uid, [('parent_id', 'in', ids), ('is_correct', '=', True)], context=context)
206         for answer in self.browse(cr, uid, ans_ids, context=context):
207             res[answer.parent_id.id] = True
208         return res
209
210     def _is_self_reply(self, cr, uid, ids, field_name, arg, context=None):
211         res = dict.fromkeys(ids, False)
212         for post in self.browse(cr, uid, ids, context=context):
213             res[post.id] = post.parent_id and post.parent_id.create_uid == post.create_uid or False
214         return res
215
216     def _get_post_karma_rights(self, cr, uid, ids, field_name, arg, context=None):
217         user = self.pool['res.users'].browse(cr, uid, uid, context=context)
218         res = dict.fromkeys(ids, False)
219         for post in self.browse(cr, uid, ids, context=context):
220             res[post.id] = {
221                 'karma_ask': post.forum_id.karma_ask,
222                 'karma_answer': post.forum_id.karma_answer,
223                 'karma_accept': post.parent_id and post.parent_id.create_uid.id == uid and post.forum_id.karma_answer_accept_own or post.forum_id.karma_answer_accept_all,
224                 'karma_edit': post.create_uid.id == uid and post.forum_id.karma_edit_own or post.forum_id.karma_edit_all,
225                 'karma_close': post.create_uid.id == uid and post.forum_id.karma_close_own or post.forum_id.karma_close_all,
226                 'karma_unlink': post.create_uid.id == uid and post.forum_id.karma_unlink_own or post.forum_id.karma_unlink_all,
227                 'karma_upvote': post.forum_id.karma_upvote,
228                 'karma_downvote': post.forum_id.karma_downvote,
229                 'karma_comment': post.create_uid.id == uid and post.forum_id.karma_comment_own or post.forum_id.karma_comment_all,
230                 'karma_comment_convert': post.create_uid.id == uid and post.forum_id.karma_comment_convert_own or post.forum_id.karma_comment_convert_all,
231             }
232             res[post.id].update({
233                 'can_ask': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_ask'],
234                 'can_answer': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_answer'],
235                 'can_accept': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_accept'],
236                 'can_edit': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_edit'],
237                 'can_close': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_close'],
238                 'can_unlink': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_unlink'],
239                 'can_upvote': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_upvote'],
240                 'can_downvote': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_downvote'],
241                 'can_comment': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_comment'],
242                 'can_comment_convert': uid == SUPERUSER_ID or user.karma >= res[post.id]['karma_comment_convert'],
243             })
244         return res
245
246     _columns = {
247         'name': fields.char('Title'),
248         'forum_id': fields.many2one('forum.forum', 'Forum', required=True),
249         'content': fields.html('Content'),
250         'tag_ids': fields.many2many('forum.tag', 'forum_tag_rel', 'forum_id', 'forum_tag_id', 'Tags'),
251         'state': fields.selection([('active', 'Active'), ('close', 'Close'), ('offensive', 'Offensive')], 'Status'),
252         'views': fields.integer('Number of Views'),
253         'active': fields.boolean('Active'),
254         'type': fields.selection([('question', 'Question'), ('link', 'Article'), ('discussion', 'Discussion')], 'Type'),
255         'relevancy': fields.function(
256             _get_post_relevancy, string="Relevancy", type='float',
257             store={
258                 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['vote_ids'], 10),
259                 'forum.post.vote': (_get_post_from_vote, [], 10),
260             }),
261         'is_correct': fields.boolean('Valid Answer', help='Correct Answer or Answer on this question accepted.'),
262         'website_message_ids': fields.one2many(
263             'mail.message', 'res_id',
264             domain=lambda self: [
265                 '&', ('model', '=', self._name), ('type', 'in', ['email', 'comment'])
266             ],
267             string='Post Messages', help="Comments on forum post",
268         ),
269         # history
270         'create_date': fields.datetime('Asked on', select=True, readonly=True),
271         'create_uid': fields.many2one('res.users', 'Created by', select=True, readonly=True),
272         'write_date': fields.datetime('Update on', select=True, readonly=True),
273         'write_uid': fields.many2one('res.users', 'Updated by', select=True, readonly=True),
274         # vote fields
275         'vote_ids': fields.one2many('forum.post.vote', 'post_id', 'Votes'),
276         'user_vote': fields.function(_get_user_vote, string='My Vote', type='integer'),
277         'vote_count': fields.function(
278             _get_vote_count, string="Votes", type='integer',
279             store={
280                 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['vote_ids'], 10),
281                 'forum.post.vote': (_get_post_from_vote, [], 10),
282             }),
283         # favorite fields
284         'favourite_ids': fields.many2many('res.users', string='Favourite'),
285         'user_favourite': fields.function(_get_user_favourite, string="My Favourite", type='boolean'),
286         'favourite_count': fields.function(
287             _get_favorite_count, string='Favorite Count', type='integer',
288             store={
289                 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['favourite_ids'], 10),
290             }),
291         # hierarchy
292         'parent_id': fields.many2one('forum.post', 'Question', ondelete='cascade'),
293         'self_reply': fields.function(
294             _is_self_reply, 'Reply to own question', type='boolean',
295             store={
296                 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['parent_id', 'create_uid'], 10),
297             }),
298         'child_ids': fields.one2many('forum.post', 'parent_id', 'Answers'),
299         'child_count': fields.function(
300             _get_child_count, string="Answers", type='integer',
301             store={
302                 'forum.post': (_get_post_from_hierarchy, ['parent_id', 'child_ids'], 10),
303             }),
304         'uid_has_answered': fields.function(
305             _get_uid_answered, string='Has Answered', type='boolean',
306         ),
307         'has_validated_answer': fields.function(
308             _get_has_validated_answer, string='Has a Validated Answered', type='boolean',
309             store={
310                 'forum.post': (_get_post_from_hierarchy, ['parent_id', 'child_ids', 'is_correct'], 10),
311             }
312         ),
313         # closing
314         'closed_reason_id': fields.many2one('forum.post.reason', 'Reason'),
315         'closed_uid': fields.many2one('res.users', 'Closed by', select=1),
316         'closed_date': fields.datetime('Closed on', readonly=True),
317         # karma
318         'karma_ask': fields.function(_get_post_karma_rights, string='Karma to ask', type='integer', multi='_get_post_karma_rights'),
319         'karma_answer': fields.function(_get_post_karma_rights, string='Karma to answer', type='integer', multi='_get_post_karma_rights'),
320         'karma_accept': fields.function(_get_post_karma_rights, string='Karma to accept this answer', type='integer', multi='_get_post_karma_rights'),
321         'karma_edit': fields.function(_get_post_karma_rights, string='Karma to edit', type='integer', multi='_get_post_karma_rights'),
322         'karma_close': fields.function(_get_post_karma_rights, string='Karma to close', type='integer', multi='_get_post_karma_rights'),
323         'karma_unlink': fields.function(_get_post_karma_rights, string='Karma to unlink', type='integer', multi='_get_post_karma_rights'),
324         'karma_upvote': fields.function(_get_post_karma_rights, string='Karma to upvote', type='integer', multi='_get_post_karma_rights'),
325         'karma_downvote': fields.function(_get_post_karma_rights, string='Karma to downvote', type='integer', multi='_get_post_karma_rights'),
326         'karma_comment': fields.function(_get_post_karma_rights, string='Karma to comment', type='integer', multi='_get_post_karma_rights'),
327         'karma_comment_convert': fields.function(_get_post_karma_rights, string='karma to convert as a comment', type='integer', multi='_get_post_karma_rights'),
328         # access rights
329         'can_ask': fields.function(_get_post_karma_rights, string='Can Ask', type='boolean', multi='_get_post_karma_rights'),
330         'can_answer': fields.function(_get_post_karma_rights, string='Can Answer', type='boolean', multi='_get_post_karma_rights'),
331         'can_accept': fields.function(_get_post_karma_rights, string='Can Accept', type='boolean', multi='_get_post_karma_rights'),
332         'can_edit': fields.function(_get_post_karma_rights, string='Can Edit', type='boolean', multi='_get_post_karma_rights'),
333         'can_close': fields.function(_get_post_karma_rights, string='Can Close', type='boolean', multi='_get_post_karma_rights'),
334         'can_unlink': fields.function(_get_post_karma_rights, string='Can Unlink', type='boolean', multi='_get_post_karma_rights'),
335         'can_upvote': fields.function(_get_post_karma_rights, string='Can Upvote', type='boolean', multi='_get_post_karma_rights'),
336         'can_downvote': fields.function(_get_post_karma_rights, string='Can Downvote', type='boolean', multi='_get_post_karma_rights'),
337         'can_comment': fields.function(_get_post_karma_rights, string='Can Comment', type='boolean', multi='_get_post_karma_rights'),
338         'can_comment_convert': fields.function(_get_post_karma_rights, string='Can Convert to Comment', type='boolean', multi='_get_post_karma_rights'),
339     }
340
341     _defaults = {
342         'state': 'active',
343         'views': 0,
344         'active': True,
345         'type': 'question',
346         'vote_ids': list(),
347         'favourite_ids': list(),
348         'child_ids': list(),
349     }
350
351     def create(self, cr, uid, vals, context=None):
352         if context is None:
353             context = {}
354         create_context = dict(context, mail_create_nolog=True)
355         post_id = super(Post, self).create(cr, uid, vals, context=create_context)
356         post = self.browse(cr, SUPERUSER_ID, post_id, context=context)  # SUPERUSER_ID to avoid read access rights issues when creating
357         # deleted or closed questions
358         if post.parent_id and (post.parent_id.state == 'close' or post.parent_id.active == False):
359             osv.except_osv(_('Error !'), _('Posting answer on [Deleted] or [Closed] question is prohibited'))
360         # karma-based access
361         if post.parent_id and not post.can_ask:
362             raise KarmaError('Not enough karma to create a new question')
363         elif not post.parent_id and not post.can_answer:
364             raise KarmaError('Not enough karma to answer to a question')
365         # messaging and chatter
366         base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
367         if post.parent_id:
368             body = _(
369                 '<p>A new answer for <i>%s</i> has been posted. <a href="%s/forum/%s/question/%s">Click here to access the post.</a></p>' %
370                 (post.parent_id.name, base_url, slug(post.parent_id.forum_id), slug(post.parent_id))
371             )
372             self.message_post(cr, uid, post.parent_id.id, subject=_('Re: %s') % post.parent_id.name, body=body, subtype='website_forum.mt_answer_new', context=context)
373         else:
374             body = _(
375                 '<p>A new question <i>%s</i> has been asked on %s. <a href="%s/forum/%s/question/%s">Click here to access the question.</a></p>' %
376                 (post.name, post.forum_id.name, base_url, slug(post.forum_id), slug(post))
377             )
378             self.message_post(cr, uid, post_id, subject=post.name, body=body, subtype='website_forum.mt_question_new', context=context)
379             self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_question_new, context=context)
380         return post_id
381
382     def write(self, cr, uid, ids, vals, context=None):
383         posts = self.browse(cr, uid, ids, context=context)
384         if 'state' in vals:
385             if vals['state'] in ['active', 'close'] and any(not post.can_close for post in posts):
386                 raise KarmaError('Not enough karma to close or reopen a post.')
387         if 'active' in vals:
388             if any(not post.can_unlink for post in posts):
389                 raise KarmaError('Not enough karma to delete or reactivate a post')
390         if 'is_correct' in vals:
391             if any(not post.can_accept for post in posts):
392                 raise KarmaError('Not enough karma to accept or refuse an answer')
393             # update karma except for self-acceptance
394             mult = 1 if vals['is_correct'] else -1
395             for post in self.browse(cr, uid, ids, context=context):
396                 if vals['is_correct'] != post.is_correct and post.create_uid.id != uid:
397                     self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id], post.forum_id.karma_gen_answer_accepted * mult, context=context)
398                     self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_answer_accept * mult, context=context)
399         if any(key not in ['state', 'active', 'is_correct', 'closed_uid', 'closed_date', 'closed_reason_id'] for key in vals.keys()) and any(not post.can_edit for post in posts):
400             raise KarmaError('Not enough karma to edit a post.')
401
402         res = super(Post, self).write(cr, uid, ids, vals, context=context)
403         # if post content modify, notify followers
404         if 'content' in vals or 'name' in vals:
405             for post in posts:
406                 if post.parent_id:
407                     body, subtype = _('Answer Edited'), 'website_forum.mt_answer_edit'
408                     obj_id = post.parent_id.id
409                 else:
410                     body, subtype = _('Question Edited'), 'website_forum.mt_question_edit'
411                     obj_id = post.id
412                 self.message_post(cr, uid, obj_id, body=body, subtype=subtype, context=context)
413         return res
414
415     def close(self, cr, uid, ids, reason_id, context=None):
416         if any(post.parent_id for post in self.browse(cr, uid, ids, context=context)):
417             return False
418         return self.pool['forum.post'].write(cr, uid, ids, {
419             'state': 'close',
420             'closed_uid': uid,
421             'closed_date': datetime.today().strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT),
422             'closed_reason_id': reason_id,
423         }, context=context)
424
425     def unlink(self, cr, uid, ids, context=None):
426         posts = self.browse(cr, uid, ids, context=context)
427         if any(not post.can_unlink for post in posts):
428             raise KarmaError('Not enough karma to unlink a post')
429         # if unlinking an answer with accepted answer: remove provided karma
430         for post in posts:
431             if post.is_correct:
432                 self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id], post.forum_id.karma_gen_answer_accepted * -1, context=context)
433                 self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_answer_accept * -1, context=context)
434         return super(Post, self).unlink(cr, uid, ids, context=context)
435
436     def vote(self, cr, uid, ids, upvote=True, context=None):
437         posts = self.browse(cr, uid, ids, context=context)
438
439         if upvote and any(not post.can_upvote for post in posts):
440             raise KarmaError('Not enough karma to upvote.')
441         elif not upvote and any(not post.can_downvote for post in posts):
442             raise KarmaError('Not enough karma to downvote.')
443
444         Vote = self.pool['forum.post.vote']
445         vote_ids = Vote.search(cr, uid, [('post_id', 'in', ids), ('user_id', '=', uid)], context=context)
446         new_vote = '1' if upvote else '-1'
447         voted_forum_ids = set()
448         if vote_ids:
449             for vote in Vote.browse(cr, uid, vote_ids, context=context):
450                 if upvote:
451                     new_vote = '0' if vote.vote == '-1' else '1'
452                 else:
453                     new_vote = '0' if vote.vote == '1' else '-1'
454                 Vote.write(cr, uid, vote_ids, {'vote': new_vote}, context=context)
455                 voted_forum_ids.add(vote.post_id.id)
456         for post_id in set(ids) - voted_forum_ids:
457             for post_id in ids:
458                 Vote.create(cr, uid, {'post_id': post_id, 'vote': new_vote}, context=context)
459         return {'vote_count': self._get_vote_count(cr, uid, ids, None, None, context=context)[ids[0]], 'user_vote': new_vote}
460
461     def convert_answer_to_comment(self, cr, uid, id, context=None):
462         """ Tools to convert an answer (forum.post) to a comment (mail.message).
463         The original post is unlinked and a new comment is posted on the question
464         using the post create_uid as the comment's author. """
465         post = self.browse(cr, SUPERUSER_ID, id, context=context)
466         if not post.parent_id:
467             return False
468
469         # karma-based action check: use the post field that computed own/all value
470         if not post.can_comment_convert:
471             raise KarmaError('Not enough karma to convert an answer to a comment')
472
473         # post the message
474         question = post.parent_id
475         values = {
476             'author_id': post.create_uid.partner_id.id,
477             'body': html2plaintext(post.content),
478             'type': 'comment',
479             'subtype': 'mail.mt_comment',
480             'date': post.create_date,
481         }
482         message_id = self.pool['forum.post'].message_post(
483             cr, uid, question.id,
484             context=dict(context, mail_create_nosubcribe=True),
485             **values)
486
487         # unlink the original answer, using SUPERUSER_ID to avoid karma issues
488         self.pool['forum.post'].unlink(cr, SUPERUSER_ID, [post.id], context=context)
489
490         return message_id
491
492     def convert_comment_to_answer(self, cr, uid, message_id, default=None, context=None):
493         """ Tool to convert a comment (mail.message) into an answer (forum.post).
494         The original comment is unlinked and a new answer from the comment's author
495         is created. Nothing is done if the comment's author already answered the
496         question. """
497         comment = self.pool['mail.message'].browse(cr, SUPERUSER_ID, message_id, context=context)
498         post = self.pool['forum.post'].browse(cr, uid, comment.res_id, context=context)
499         user = self.pool['res.users'].browse(cr, uid, uid, context=context)
500         if not comment.author_id or not comment.author_id.user_ids:  # only comment posted by users can be converted
501             return False
502
503         # karma-based action check: must check the message's author to know if own / all
504         karma_convert = comment.author_id.id == user.partner_id.id and post.forum_id.karma_comment_convert_own or post.forum_id.karma_comment_convert_all
505         can_convert = uid == SUPERUSER_ID or user.karma >= karma_convert
506         if not can_convert:
507             raise KarmaError('Not enough karma to convert a comment to an answer')
508
509         # check the message's author has not already an answer
510         question = post.parent_id if post.parent_id else post
511         post_create_uid = comment.author_id.user_ids[0]
512         if any(answer.create_uid.id == post_create_uid.id for answer in question.child_ids):
513             return False
514
515         # create the new post
516         post_values = {
517             'forum_id': question.forum_id.id,
518             'content': comment.body,
519             'parent_id': question.id,
520         }
521         # done with the author user to have create_uid correctly set
522         new_post_id = self.pool['forum.post'].create(cr, post_create_uid.id, post_values, context=context)
523
524         # delete comment
525         self.pool['mail.message'].unlink(cr, SUPERUSER_ID, [comment.id], context=context)
526
527         return new_post_id
528
529     def unlink_comment(self, cr, uid, id, message_id, context=None):
530         comment = self.pool['mail.message'].browse(cr, SUPERUSER_ID, message_id, context=context)
531         post = self.pool['forum.post'].browse(cr, uid, id, context=context)
532         user = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context)
533         if not comment.model == 'forum.post' or not comment.res_id == id:
534             return False
535
536         # karma-based action check: must check the message's author to know if own or all
537         karma_unlink = comment.author_id.id == user.partner_id.id and post.forum_id.karma_comment_unlink_own or post.forum_id.karma_comment_unlink_all
538         can_unlink = uid == SUPERUSER_ID or user.karma >= karma_unlink
539         if not can_unlink:
540             raise KarmaError('Not enough karma to unlink a comment')
541
542         return self.pool['mail.message'].unlink(cr, SUPERUSER_ID, [message_id], context=context)
543
544     def set_viewed(self, cr, uid, ids, context=None):
545         cr.execute("""UPDATE forum_post SET views = views+1 WHERE id IN %s""", (tuple(ids),))
546         return True
547
548     def _get_access_link(self, cr, uid, mail, partner, context=None):
549         post = self.pool['forum.post'].browse(cr, uid, mail.res_id, context=context)
550         res_id = post.parent_id and "%s#answer-%s" % (post.parent_id.id, post.id) or post.id
551         return "/forum/%s/question/%s" % (post.forum_id.id, res_id)
552
553
554 class PostReason(osv.Model):
555     _name = "forum.post.reason"
556     _description = "Post Closing Reason"
557     _order = 'name'
558     _columns = {
559         'name': fields.char('Post Reason', required=True, translate=True),
560     }
561
562
563 class Vote(osv.Model):
564     _name = 'forum.post.vote'
565     _description = 'Vote'
566     _columns = {
567         'post_id': fields.many2one('forum.post', 'Post', ondelete='cascade', required=True),
568         'user_id': fields.many2one('res.users', 'User', required=True),
569         'vote': fields.selection([('1', '1'), ('-1', '-1'), ('0', '0')], 'Vote', required=True),
570         'create_date': fields.datetime('Create Date', select=True, readonly=True),
571
572         # TODO master: store these two
573         'forum_id': fields.related('post_id', 'forum_id', type='many2one', relation='forum.forum', string='Forum'),
574         'recipient_id': fields.related('post_id', 'create_uid', type='many2one', relation='res.users', string='To', help="The user receiving the vote"),
575     }
576     _defaults = {
577         'user_id': lambda self, cr, uid, ctx: uid,
578         'vote': lambda *args: '1',
579     }
580
581     def _get_karma_value(self, old_vote, new_vote, up_karma, down_karma):
582         _karma_upd = {
583             '-1': {'-1': 0, '0': -1 * down_karma, '1': -1 * down_karma + up_karma},
584             '0': {'-1': 1 * down_karma, '0': 0, '1': up_karma},
585             '1': {'-1': -1 * up_karma + down_karma, '0': -1 * up_karma, '1': 0}
586         }
587         return _karma_upd[old_vote][new_vote]
588
589     def create(self, cr, uid, vals, context=None):
590         vote_id = super(Vote, self).create(cr, uid, vals, context=context)
591         vote = self.browse(cr, uid, vote_id, context=context)
592         if vote.post_id.parent_id:
593             karma_value = self._get_karma_value('0', vote.vote, vote.forum_id.karma_gen_answer_upvote, vote.forum_id.karma_gen_answer_downvote)
594         else:
595             karma_value = self._get_karma_value('0', vote.vote, vote.forum_id.karma_gen_question_upvote, vote.forum_id.karma_gen_question_downvote)
596         self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [vote.recipient_id.id], karma_value, context=context)
597         return vote_id
598
599     def write(self, cr, uid, ids, values, context=None):
600         if 'vote' in values:
601             for vote in self.browse(cr, uid, ids, context=context):
602                 if vote.post_id.parent_id:
603                     karma_value = self._get_karma_value(vote.vote, values['vote'], vote.forum_id.karma_gen_answer_upvote, vote.forum_id.karma_gen_answer_downvote)
604                 else:
605                     karma_value = self._get_karma_value(vote.vote, values['vote'], vote.forum_id.karma_gen_question_upvote, vote.forum_id.karma_gen_question_downvote)
606                 self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [vote.recipient_id.id], karma_value, context=context)
607         res = super(Vote, self).write(cr, uid, ids, values, context=context)
608         return res
609
610
611 class Tags(osv.Model):
612     _name = "forum.tag"
613     _description = "Tag"
614     _inherit = ['website.seo.metadata']
615
616     def _get_posts_count(self, cr, uid, ids, field_name, arg, context=None):
617         return dict((tag_id, self.pool['forum.post'].search_count(cr, uid, [('tag_ids', 'in', tag_id)], context=context)) for tag_id in ids)
618
619     def _get_tag_from_post(self, cr, uid, ids, context=None):
620         return list(set(
621             [tag.id for post in self.pool['forum.post'].browse(cr, SUPERUSER_ID, ids, context=context) for tag in post.tag_ids]
622         ))
623
624     _columns = {
625         'name': fields.char('Name', required=True),
626         'forum_id': fields.many2one('forum.forum', 'Forum', required=True),
627         'post_ids': fields.many2many('forum.post', 'forum_tag_rel', 'tag_id', 'post_id', 'Posts'),
628         'posts_count': fields.function(
629             _get_posts_count, type='integer', string="Number of Posts",
630             store={
631                 'forum.post': (_get_tag_from_post, ['tag_ids'], 10),
632             }
633         ),
634         'create_uid': fields.many2one('res.users', 'Created by', readonly=True),
635     }