e58b1f6600fa1e23da08c9cf904f809c2ed181dc
[odoo/odoo.git] / addons / website_forum / models / forum.py
1 # -*- coding: utf-8 -*-
2
3 from datetime import datetime
4 import uuid
5 from werkzeug.exceptions import Forbidden
6
7 import logging
8 import openerp
9
10 from openerp import api, tools
11 from openerp import SUPERUSER_ID
12 from openerp.addons.website.models.website import slug
13 from openerp.exceptions import Warning
14 from openerp.osv import osv, fields
15 from openerp.tools import html2plaintext
16 from openerp.tools.translate import _
17
18 _logger = logging.getLogger(__name__)
19
20 class KarmaError(Forbidden):
21     """ Karma-related error, used for forum and posts. """
22     pass
23
24
25 class Forum(osv.Model):
26     """TDE TODO: set karma values for actions dynamic for a given forum"""
27     _name = 'forum.forum'
28     _description = 'Forums'
29     _inherit = ['mail.thread', 'website.seo.metadata']
30
31     def init(self, cr):
32         """ Add forum uuid for user email validation. """
33         forum_uuids = self.pool['ir.config_parameter'].search(cr, SUPERUSER_ID, [('key', '=', 'website_forum.uuid')])
34         if not forum_uuids:
35             self.pool['ir.config_parameter'].set_param(cr, SUPERUSER_ID, 'website_forum.uuid', str(uuid.uuid4()), ['base.group_system'])
36
37     _columns = {
38         'name': fields.char('Name', required=True, translate=True),
39         'faq': fields.html('Guidelines'),
40         'description': fields.html('Description'),
41         # karma generation
42         'karma_gen_question_new': fields.integer('Asking a question'),
43         'karma_gen_question_upvote': fields.integer('Question upvoted'),
44         'karma_gen_question_downvote': fields.integer('Question downvoted'),
45         'karma_gen_answer_upvote': fields.integer('Answer upvoted'),
46         'karma_gen_answer_downvote': fields.integer('Answer downvoted'),
47         'karma_gen_answer_accept': fields.integer('Accepting an answer'),
48         'karma_gen_answer_accepted': fields.integer('Answer accepted'),
49         'karma_gen_answer_flagged': fields.integer('Answer flagged'),
50         # karma-based actions
51         'karma_ask': fields.integer('Ask a 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 answer to all questions'),
63         'karma_editor_link_files': fields.integer('Linking files (Editor)'),
64         'karma_editor_clickable_link': fields.integer('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 comments 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         'description': 'This community is for professionals and enthusiasts of our products and services.',
83         'faq': _get_default_faq,
84         'karma_gen_question_new': 0,  # set to null for anti spam protection
85         'karma_gen_question_upvote': 5,
86         'karma_gen_question_downvote': -2,
87         'karma_gen_answer_upvote': 10,
88         'karma_gen_answer_downvote': -2,
89         'karma_gen_answer_accept': 2,
90         'karma_gen_answer_accepted': 15,
91         'karma_gen_answer_flagged': -100,
92         'karma_ask': 3,  # set to not null for anti spam protection
93         'karma_answer': 3,  # set to not null for anti spam protection
94         'karma_edit_own': 1,
95         'karma_edit_all': 300,
96         'karma_close_own': 100,
97         'karma_close_all': 500,
98         'karma_unlink_own': 500,
99         'karma_unlink_all': 1000,
100         'karma_upvote': 5,
101         'karma_downvote': 50,
102         'karma_answer_accept_own': 20,
103         'karma_answer_accept_all': 500,
104         'karma_editor_link_files': 20,
105         'karma_editor_clickable_link': 20,
106         'karma_comment_own': 3,
107         'karma_comment_all': 5,
108         'karma_comment_convert_own': 50,
109         'karma_comment_convert_all': 500,
110         'karma_comment_unlink_own': 50,
111         'karma_comment_unlink_all': 500,
112         'karma_retag': 75,
113         'karma_flag': 500,
114     }
115
116     def create(self, cr, uid, values, context=None):
117         if context is None:
118             context = {}
119         create_context = dict(context, mail_create_nolog=True)
120         return super(Forum, self).create(cr, uid, values, context=create_context)
121
122     def _tag_to_write_vals(self, cr, uid, tags='', context=None):
123         User = self.pool['res.users']
124         Tag = self.pool['forum.tag']
125         post_tags = []
126         for tag in filter(None, tags.split(',')):
127             if tag.startswith('_'):  # it's a new tag
128                 # check that not arleady created meanwhile or maybe excluded by the limit on the search
129                 tag_ids = Tag.search(cr, uid, [('name', '=', tag[1:])], context=context)
130                 if tag_ids:
131                     post_tags.append((4, int(tag_ids[0])))
132                 else:
133                     # check if user have Karma needed to create need tag
134                     user = User.browse(cr, uid, uid, context=context)
135                     if user.exists() and user.karma >= self.karma_retag:
136                             post_tags.append((0, 0, {'name': tag[1:], 'forum_id': self.id}))
137             else:
138                 post_tags.append((4, int(tag)))
139         return post_tags
140
141
142 class Post(osv.Model):
143     _name = 'forum.post'
144     _description = 'Forum Post'
145     _inherit = ['mail.thread', 'website.seo.metadata']
146     _order = "is_correct DESC, vote_count DESC, write_date DESC"
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         'is_correct': fields.boolean('Valid Answer', help='Correct Answer or Answer on this question accepted.'),
255         'website_message_ids': fields.one2many(
256             'mail.message', 'res_id',
257             domain=lambda self: [
258                 '&', ('model', '=', self._name), ('type', 'in', ['email', 'comment'])
259             ],
260             string='Post Messages', help="Comments on forum post",
261         ),
262         # history
263         'create_date': fields.datetime('Asked on', select=True, readonly=True),
264         'create_uid': fields.many2one('res.users', 'Created by', select=True, readonly=True),
265         'write_date': fields.datetime('Update on', select=True, readonly=True),
266         'write_uid': fields.many2one('res.users', 'Updated by', select=True, readonly=True),
267         # vote fields
268         'vote_ids': fields.one2many('forum.post.vote', 'post_id', 'Votes'),
269         'user_vote': fields.function(_get_user_vote, string='My Vote', type='integer'),
270         'vote_count': fields.function(
271             _get_vote_count, string="Votes", type='integer',
272             store={
273                 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['vote_ids'], 10),
274                 'forum.post.vote': (_get_post_from_vote, [], 10),
275             }),
276         # favorite fields
277         'favourite_ids': fields.many2many('res.users', string='Favourite'),
278         'user_favourite': fields.function(_get_user_favourite, string="My Favourite", type='boolean'),
279         'favourite_count': fields.function(
280             _get_favorite_count, string='Favorite Count', type='integer',
281             store={
282                 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['favourite_ids'], 10),
283             }),
284         # hierarchy
285         'parent_id': fields.many2one('forum.post', 'Question', ondelete='cascade'),
286         'self_reply': fields.function(
287             _is_self_reply, 'Reply to own question', type='boolean',
288             store={
289                 'forum.post': (lambda self, cr, uid, ids, c={}: ids, ['parent_id', 'create_uid'], 10),
290             }),
291         'child_ids': fields.one2many('forum.post', 'parent_id', 'Answers'),
292         'child_count': fields.function(
293             _get_child_count, string="Answers", type='integer',
294             store={
295                 'forum.post': (_get_post_from_hierarchy, ['parent_id', 'child_ids'], 10),
296             }),
297         'uid_has_answered': fields.function(
298             _get_uid_answered, string='Has Answered', type='boolean',
299         ),
300         'has_validated_answer': fields.function(
301             _get_has_validated_answer, string='Has a Validated Answered', type='boolean',
302             store={
303                 'forum.post': (_get_post_from_hierarchy, ['parent_id', 'child_ids', 'is_correct'], 10),
304             }
305         ),
306         # closing
307         'closed_reason_id': fields.many2one('forum.post.reason', 'Reason'),
308         'closed_uid': fields.many2one('res.users', 'Closed by', select=1),
309         'closed_date': fields.datetime('Closed on', readonly=True),
310         # karma
311         'karma_ask': fields.function(_get_post_karma_rights, string='Karma to ask', type='integer', multi='_get_post_karma_rights'),
312         'karma_answer': fields.function(_get_post_karma_rights, string='Karma to answer', type='integer', multi='_get_post_karma_rights'),
313         'karma_accept': fields.function(_get_post_karma_rights, string='Karma to accept this answer', type='integer', multi='_get_post_karma_rights'),
314         'karma_edit': fields.function(_get_post_karma_rights, string='Karma to edit', type='integer', multi='_get_post_karma_rights'),
315         'karma_close': fields.function(_get_post_karma_rights, string='Karma to close', type='integer', multi='_get_post_karma_rights'),
316         'karma_unlink': fields.function(_get_post_karma_rights, string='Karma to unlink', type='integer', multi='_get_post_karma_rights'),
317         'karma_upvote': fields.function(_get_post_karma_rights, string='Karma to upvote', type='integer', multi='_get_post_karma_rights'),
318         'karma_downvote': fields.function(_get_post_karma_rights, string='Karma to downvote', type='integer', multi='_get_post_karma_rights'),
319         'karma_comment': fields.function(_get_post_karma_rights, string='Karma to comment', type='integer', multi='_get_post_karma_rights'),
320         'karma_comment_convert': fields.function(_get_post_karma_rights, string='karma to convert as a comment', type='integer', multi='_get_post_karma_rights'),
321         # access rights
322         'can_ask': fields.function(_get_post_karma_rights, string='Can Ask', type='boolean', multi='_get_post_karma_rights'),
323         'can_answer': fields.function(_get_post_karma_rights, string='Can Answer', type='boolean', multi='_get_post_karma_rights'),
324         'can_accept': fields.function(_get_post_karma_rights, string='Can Accept', type='boolean', multi='_get_post_karma_rights'),
325         'can_edit': fields.function(_get_post_karma_rights, string='Can Edit', type='boolean', multi='_get_post_karma_rights'),
326         'can_close': fields.function(_get_post_karma_rights, string='Can Close', type='boolean', multi='_get_post_karma_rights'),
327         'can_unlink': fields.function(_get_post_karma_rights, string='Can Unlink', type='boolean', multi='_get_post_karma_rights'),
328         'can_upvote': fields.function(_get_post_karma_rights, string='Can Upvote', type='boolean', multi='_get_post_karma_rights'),
329         'can_downvote': fields.function(_get_post_karma_rights, string='Can Downvote', type='boolean', multi='_get_post_karma_rights'),
330         'can_comment': fields.function(_get_post_karma_rights, string='Can Comment', type='boolean', multi='_get_post_karma_rights'),
331         'can_comment_convert': fields.function(_get_post_karma_rights, string='Can Convert to Comment', type='boolean', multi='_get_post_karma_rights'),
332     }
333
334     _defaults = {
335         'state': 'active',
336         'views': 0,
337         'active': True,
338         'vote_ids': list(),
339         'favourite_ids': list(),
340         'child_ids': list(),
341     }
342
343     def create(self, cr, uid, vals, context=None):
344         if context is None:
345             context = {}
346         create_context = dict(context, mail_create_nolog=True)
347         post_id = super(Post, self).create(cr, uid, vals, context=create_context)
348         post = self.browse(cr, uid, post_id, context=context)
349         # karma-based access
350         if not post.parent_id and not post.can_ask:
351             raise KarmaError('Not enough karma to create a new question')
352         elif post.parent_id and not post.can_answer:
353             raise KarmaError('Not enough karma to answer to a question')
354         # messaging and chatter
355         base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
356         if post.parent_id:
357             body = _(
358                 '<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>' %
359                 (post.parent_id.name, base_url, slug(post.parent_id.forum_id), slug(post.parent_id))
360             )
361             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)
362         else:
363             body = _(
364                 '<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>' %
365                 (post.name, post.forum_id.name, base_url, slug(post.forum_id), slug(post))
366             )
367             self.message_post(cr, uid, post_id, subject=post.name, body=body, subtype='website_forum.mt_question_new', context=context)
368             self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_question_new, context=context)
369         return post_id
370
371     def write(self, cr, uid, ids, vals, context=None):
372         posts = self.browse(cr, uid, ids, context=context)
373         if 'state' in vals:
374             if vals['state'] in ['active', 'close'] and any(not post.can_close for post in posts):
375                 raise KarmaError('Not enough karma to close or reopen a post.')
376         if 'active' in vals:
377             if any(not post.can_unlink for post in posts):
378                 raise KarmaError('Not enough karma to delete or reactivate a post')
379         if 'is_correct' in vals:
380             if any(not post.can_accept for post in posts):
381                 raise KarmaError('Not enough karma to accept or refuse an answer')
382             # update karma except for self-acceptance
383             mult = 1 if vals['is_correct'] else -1
384             for post in self.browse(cr, uid, ids, context=context):
385                 if vals['is_correct'] != post.is_correct and post.create_uid.id != uid:
386                     self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id], post.forum_id.karma_gen_answer_accepted * mult, context=context)
387                     self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_answer_accept * mult, context=context)
388         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):
389             raise KarmaError('Not enough karma to edit a post.')
390
391         res = super(Post, self).write(cr, uid, ids, vals, context=context)
392         # if post content modify, notify followers
393         if 'content' in vals or 'name' in vals:
394             for post in posts:
395                 if post.parent_id:
396                     body, subtype = _('Answer Edited'), 'website_forum.mt_answer_edit'
397                     obj_id = post.parent_id.id
398                 else:
399                     body, subtype = _('Question Edited'), 'website_forum.mt_question_edit'
400                     obj_id = post.id
401                 self.message_post(cr, uid, obj_id, body=body, subtype=subtype, context=context)
402         return res
403
404
405     def reopen(self, cr, uid, ids, context=None):
406         if any(post.parent_id or post.state != 'close'
407                     for post in self.browse(cr, uid, ids, context=context)):
408             return False
409
410         reason_offensive = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_7')
411         reason_spam = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_8')
412         for post in self.browse(cr, uid, ids, context=context):
413             if post.closed_reason_id.id in (reason_offensive, reason_spam):
414                 _logger.info('Upvoting user <%s>, reopening spam/offensive question',
415                              post.create_uid)
416                 # TODO: in master, consider making this a tunable karma parameter
417                 self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id],
418                                                  post.forum_id.karma_gen_question_downvote * -5,
419                                                  context=context)
420         self.pool['forum.post'].write(cr, SUPERUSER_ID, ids, {'state': 'active'}, context=context)
421
422     def close(self, cr, uid, ids, reason_id, context=None):
423         if any(post.parent_id for post in self.browse(cr, uid, ids, context=context)):
424             return False
425
426         reason_offensive = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_7')
427         reason_spam = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'website_forum.reason_8')
428         if reason_id in (reason_offensive, reason_spam):
429             for post in self.browse(cr, uid, ids, context=context):
430                 _logger.info('Downvoting user <%s> for posting spam/offensive contents',
431                              post.create_uid)
432                 # TODO: in master, consider making this a tunable karma parameter
433                 self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id],
434                                                  post.forum_id.karma_gen_question_downvote * 5,
435                                                  context=context)
436
437         self.pool['forum.post'].write(cr, uid, ids, {
438             'state': 'close',
439             'closed_uid': uid,
440             'closed_date': datetime.today().strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT),
441             'closed_reason_id': reason_id,
442         }, context=context)
443
444     def unlink(self, cr, uid, ids, context=None):
445         posts = self.browse(cr, uid, ids, context=context)
446         if any(not post.can_unlink for post in posts):
447             raise KarmaError('Not enough karma to unlink a post')
448         # if unlinking an answer with accepted answer: remove provided karma
449         for post in posts:
450             if post.is_correct:
451                 self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [post.create_uid.id], post.forum_id.karma_gen_answer_accepted * -1, context=context)
452                 self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [uid], post.forum_id.karma_gen_answer_accept * -1, context=context)
453         return super(Post, self).unlink(cr, uid, ids, context=context)
454
455     def vote(self, cr, uid, ids, upvote=True, context=None):
456         Vote = self.pool['forum.post.vote']
457         vote_ids = Vote.search(cr, uid, [('post_id', 'in', ids), ('user_id', '=', uid)], context=context)
458         new_vote = '1' if upvote else '-1'
459         voted_forum_ids = set()
460         if vote_ids:
461             for vote in Vote.browse(cr, uid, vote_ids, context=context):
462                 if upvote:
463                     new_vote = '0' if vote.vote == '-1' else '1'
464                 else:
465                     new_vote = '0' if vote.vote == '1' else '-1'
466                 Vote.write(cr, uid, vote_ids, {'vote': new_vote}, context=context)
467                 voted_forum_ids.add(vote.post_id.id)
468         for post_id in set(ids) - voted_forum_ids:
469             for post_id in ids:
470                 Vote.create(cr, uid, {'post_id': post_id, 'vote': new_vote}, context=context)
471         return {'vote_count': self._get_vote_count(cr, uid, ids, None, None, context=context)[ids[0]], 'user_vote': new_vote}
472
473     def convert_answer_to_comment(self, cr, uid, id, context=None):
474         """ Tools to convert an answer (forum.post) to a comment (mail.message).
475         The original post is unlinked and a new comment is posted on the question
476         using the post create_uid as the comment's author. """
477         post = self.browse(cr, SUPERUSER_ID, id, context=context)
478         if not post.parent_id:
479             return False
480
481         # karma-based action check: use the post field that computed own/all value
482         if not post.can_comment_convert:
483             raise KarmaError('Not enough karma to convert an answer to a comment')
484
485         # post the message
486         question = post.parent_id
487         values = {
488             'author_id': post.create_uid.partner_id.id,
489             'body': html2plaintext(post.content),
490             'type': 'comment',
491             'subtype': 'mail.mt_comment',
492             'date': post.create_date,
493         }
494         message_id = self.pool['forum.post'].message_post(
495             cr, uid, question.id,
496             context=dict(context, mail_create_nosubcribe=True),
497             **values)
498
499         # unlink the original answer, using SUPERUSER_ID to avoid karma issues
500         self.pool['forum.post'].unlink(cr, SUPERUSER_ID, [post.id], context=context)
501
502         return message_id
503
504     def convert_comment_to_answer(self, cr, uid, message_id, default=None, context=None):
505         """ Tool to convert a comment (mail.message) into an answer (forum.post).
506         The original comment is unlinked and a new answer from the comment's author
507         is created. Nothing is done if the comment's author already answered the
508         question. """
509         comment = self.pool['mail.message'].browse(cr, SUPERUSER_ID, message_id, context=context)
510         post = self.pool['forum.post'].browse(cr, uid, comment.res_id, context=context)
511         user = self.pool['res.users'].browse(cr, uid, uid, context=context)
512         if not comment.author_id or not comment.author_id.user_ids:  # only comment posted by users can be converted
513             return False
514
515         # karma-based action check: must check the message's author to know if own / all
516         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
517         can_convert = uid == SUPERUSER_ID or user.karma >= karma_convert
518         if not can_convert:
519             raise KarmaError('Not enough karma to convert a comment to an answer')
520
521         # check the message's author has not already an answer
522         question = post.parent_id if post.parent_id else post
523         post_create_uid = comment.author_id.user_ids[0]
524         if any(answer.create_uid.id == post_create_uid.id for answer in question.child_ids):
525             return False
526
527         # create the new post
528         post_values = {
529             'forum_id': question.forum_id.id,
530             'content': comment.body,
531             'parent_id': question.id,
532         }
533         # done with the author user to have create_uid correctly set
534         new_post_id = self.pool['forum.post'].create(cr, post_create_uid.id, post_values, context=context)
535
536         # delete comment
537         self.pool['mail.message'].unlink(cr, SUPERUSER_ID, [comment.id], context=context)
538
539         return new_post_id
540
541     def unlink_comment(self, cr, uid, id, message_id, context=None):
542         comment = self.pool['mail.message'].browse(cr, SUPERUSER_ID, message_id, context=context)
543         post = self.pool['forum.post'].browse(cr, uid, id, context=context)
544         user = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context)
545         if not comment.model == 'forum.post' or not comment.res_id == id:
546             return False
547
548         # karma-based action check: must check the message's author to know if own or all
549         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
550         can_unlink = uid == SUPERUSER_ID or user.karma >= karma_unlink
551         if not can_unlink:
552             raise KarmaError('Not enough karma to unlink a comment')
553
554         return self.pool['mail.message'].unlink(cr, SUPERUSER_ID, [message_id], context=context)
555
556     def set_viewed(self, cr, uid, ids, context=None):
557         cr.execute("""UPDATE forum_post SET views = views+1 WHERE id IN %s""", (tuple(ids),))
558         return True
559
560     def _get_access_link(self, cr, uid, mail, partner, context=None):
561         post = self.pool['forum.post'].browse(cr, uid, mail.res_id, context=context)
562         res_id = post.parent_id and "%s#answer-%s" % (post.parent_id.id, post.id) or post.id
563         return "/forum/%s/question/%s" % (post.forum_id.id, res_id)
564
565     @api.cr_uid_ids_context
566     def message_post(self, cr, uid, thread_id, type='notification', subtype=None, context=None, **kwargs):
567         if thread_id and type == 'comment':  # user comments have a restriction on karma
568             if isinstance(thread_id, (list, tuple)):
569                 post_id = thread_id[0]
570             else:
571                 post_id = thread_id
572             post = self.browse(cr, uid, post_id, context=context)
573             if not post.can_comment:
574                 raise KarmaError('Not enough karma to comment')
575         return super(Post, self).message_post(cr, uid, thread_id, type=type, subtype=subtype, context=context, **kwargs)
576
577
578 class PostReason(osv.Model):
579     _name = "forum.post.reason"
580     _description = "Post Closing Reason"
581     _order = 'name'
582     _columns = {
583         'name': fields.char('Post Reason', required=True, translate=True),
584     }
585
586
587 class Vote(osv.Model):
588     _name = 'forum.post.vote'
589     _description = 'Vote'
590     _columns = {
591         'post_id': fields.many2one('forum.post', 'Post', ondelete='cascade', required=True),
592         'user_id': fields.many2one('res.users', 'User', required=True),
593         'vote': fields.selection([('1', '1'), ('-1', '-1'), ('0', '0')], 'Vote', required=True),
594         'create_date': fields.datetime('Create Date', select=True, readonly=True),
595
596         # TODO master: store these two
597         'forum_id': fields.related('post_id', 'forum_id', type='many2one', relation='forum.forum', string='Forum'),
598         'recipient_id': fields.related('post_id', 'create_uid', type='many2one', relation='res.users', string='To', help="The user receiving the vote"),
599     }
600     _defaults = {
601         'user_id': lambda self, cr, uid, ctx: uid,
602         'vote': lambda *args: '1',
603     }
604
605     def _get_karma_value(self, old_vote, new_vote, up_karma, down_karma):
606         _karma_upd = {
607             '-1': {'-1': 0, '0': -1 * down_karma, '1': -1 * down_karma + up_karma},
608             '0': {'-1': 1 * down_karma, '0': 0, '1': up_karma},
609             '1': {'-1': -1 * up_karma + down_karma, '0': -1 * up_karma, '1': 0}
610         }
611         return _karma_upd[old_vote][new_vote]
612
613     def create(self, cr, uid, vals, context=None):
614         vote_id = super(Vote, self).create(cr, uid, vals, context=context)
615         vote = self.browse(cr, uid, vote_id, context=context)
616
617         # own post check
618         if vote.user_id.id == vote.post_id.create_uid.id:
619             raise Warning('Not allowed to vote for its own post')
620         # karma check
621         if vote.vote == '1' and not vote.post_id.can_upvote:
622             raise KarmaError('Not enough karma to upvote.')
623         elif vote.vote == '-1' and not vote.post_id.can_downvote:
624             raise KarmaError('Not enough karma to downvote.')
625
626         # karma update
627         if vote.post_id.parent_id:
628             karma_value = self._get_karma_value('0', vote.vote, vote.forum_id.karma_gen_answer_upvote, vote.forum_id.karma_gen_answer_downvote)
629         else:
630             karma_value = self._get_karma_value('0', vote.vote, vote.forum_id.karma_gen_question_upvote, vote.forum_id.karma_gen_question_downvote)
631         self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [vote.recipient_id.id], karma_value, context=context)
632         return vote_id
633
634     def write(self, cr, uid, ids, values, context=None):
635         if 'vote' in values:
636             for vote in self.browse(cr, uid, ids, context=context):
637                 # own post check
638                 if vote.user_id.id == vote.post_id.create_uid.id:
639                     raise Warning('Not allowed to vote for its own post')
640                 # karma check
641                 if (values['vote'] == '1' or vote.vote == '-1' and values['vote'] == '0') and not vote.post_id.can_upvote:
642                     raise KarmaError('Not enough karma to upvote.')
643                 elif (values['vote'] == '-1' or vote.vote == '1' and values['vote'] == '0') and not vote.post_id.can_downvote:
644                     raise KarmaError('Not enough karma to downvote.')
645
646                 # karma update
647                 if vote.post_id.parent_id:
648                     karma_value = self._get_karma_value(vote.vote, values['vote'], vote.forum_id.karma_gen_answer_upvote, vote.forum_id.karma_gen_answer_downvote)
649                 else:
650                     karma_value = self._get_karma_value(vote.vote, values['vote'], vote.forum_id.karma_gen_question_upvote, vote.forum_id.karma_gen_question_downvote)
651                 self.pool['res.users'].add_karma(cr, SUPERUSER_ID, [vote.recipient_id.id], karma_value, context=context)
652         res = super(Vote, self).write(cr, uid, ids, values, context=context)
653         return res
654
655
656 class Tags(osv.Model):
657     _name = "forum.tag"
658     _description = "Tag"
659     _inherit = ['website.seo.metadata']
660
661     def _get_posts_count(self, cr, uid, ids, field_name, arg, context=None):
662         return dict((tag_id, self.pool['forum.post'].search_count(cr, uid, [('tag_ids', 'in', tag_id)], context=context)) for tag_id in ids)
663
664     def _get_tag_from_post(self, cr, uid, ids, context=None):
665         return list(set(
666             [tag.id for post in self.pool['forum.post'].browse(cr, SUPERUSER_ID, ids, context=context) for tag in post.tag_ids]
667         ))
668
669     _columns = {
670         'name': fields.char('Name', required=True),
671         'forum_id': fields.many2one('forum.forum', 'Forum', required=True),
672         'post_ids': fields.many2many('forum.post', 'forum_tag_rel', 'tag_id', 'post_id', 'Posts'),
673         'posts_count': fields.function(
674             _get_posts_count, type='integer', string="Number of Posts",
675             store={
676                 'forum.post': (_get_tag_from_post, ['tag_ids'], 10),
677             }
678         ),
679         'create_uid': fields.many2one('res.users', 'Created by', readonly=True),
680     }