[MERGE] forward port of branch 8.0 up to e883193
[odoo/odoo.git] / addons / mail / mail_message.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>)
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
19 #
20 ##############################################################################
21
22 import logging
23
24 from openerp import tools
25
26 from email.header import decode_header
27 from email.utils import formataddr
28 from openerp import SUPERUSER_ID, api
29 from openerp.osv import osv, orm, fields
30 from openerp.tools import html_email_clean
31 from openerp.tools.translate import _
32 from HTMLParser import HTMLParser
33
34 _logger = logging.getLogger(__name__)
35
36
37 """ Some tools for parsing / creating email fields """
38 def decode(text):
39     """Returns unicode() string conversion of the the given encoded smtp header text"""
40     if text:
41         text = decode_header(text.replace('\r', ''))
42         return ''.join([tools.ustr(x[0], x[1]) for x in text])
43
44 class MLStripper(HTMLParser):
45     def __init__(self):
46         self.reset()
47         self.fed = []
48     def handle_data(self, d):
49         self.fed.append(d)
50     def get_data(self):
51         return ''.join(self.fed)
52
53 def strip_tags(html):
54     s = MLStripper()
55     s.feed(html)
56     return s.get_data()
57
58 class mail_message(osv.Model):
59     """ Messages model: system notification (replacing res.log notifications),
60         comments (OpenChatter discussion) and incoming emails. """
61     _name = 'mail.message'
62     _description = 'Message'
63     _inherit = ['ir.needaction_mixin']
64     _order = 'id desc'
65     _rec_name = 'record_name'
66
67     _message_read_limit = 30
68     _message_read_fields = ['id', 'parent_id', 'model', 'res_id', 'body', 'subject', 'date', 'to_read', 'email_from',
69         'type', 'vote_user_ids', 'attachment_ids', 'author_id', 'partner_ids', 'record_name']
70     _message_record_name_length = 18
71     _message_read_more_limit = 1024
72
73     def default_get(self, cr, uid, fields, context=None):
74         # protection for `default_type` values leaking from menu action context (e.g. for invoices)
75         if context and context.get('default_type') and context.get('default_type') not in [
76                 val[0] for val in self._columns['type'].selection]:
77             context = dict(context, default_type=None)
78         return super(mail_message, self).default_get(cr, uid, fields, context=context)
79
80     def _get_to_read(self, cr, uid, ids, name, arg, context=None):
81         """ Compute if the message is unread by the current user. """
82         res = dict((id, False) for id in ids)
83         partner_id = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id
84         notif_obj = self.pool.get('mail.notification')
85         notif_ids = notif_obj.search(cr, uid, [
86             ('partner_id', 'in', [partner_id]),
87             ('message_id', 'in', ids),
88             ('is_read', '=', False),
89         ], context=context)
90         for notif in notif_obj.browse(cr, uid, notif_ids, context=context):
91             res[notif.message_id.id] = True
92         return res
93
94     def _search_to_read(self, cr, uid, obj, name, domain, context=None):
95         """ Search for messages to read by the current user. Condition is
96             inversed because we search unread message on a is_read column. """
97         return ['&', ('notification_ids.partner_id.user_ids', 'in', [uid]), ('notification_ids.is_read', '=', not domain[0][2])]
98
99     def _get_starred(self, cr, uid, ids, name, arg, context=None):
100         """ Compute if the message is unread by the current user. """
101         res = dict((id, False) for id in ids)
102         partner_id = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id
103         notif_obj = self.pool.get('mail.notification')
104         notif_ids = notif_obj.search(cr, uid, [
105             ('partner_id', 'in', [partner_id]),
106             ('message_id', 'in', ids),
107             ('starred', '=', True),
108         ], context=context)
109         for notif in notif_obj.browse(cr, uid, notif_ids, context=context):
110             res[notif.message_id.id] = True
111         return res
112
113     def _search_starred(self, cr, uid, obj, name, domain, context=None):
114         """ Search for starred messages by the current user."""
115         return ['&', ('notification_ids.partner_id.user_ids', 'in', [uid]), ('notification_ids.starred', '=', domain[0][2])]
116
117     _columns = {
118         'type': fields.selection([
119                         ('email', 'Email'),
120                         ('comment', 'Comment'),
121                         ('notification', 'System notification'),
122                         ], 'Type', size=12, 
123             help="Message type: email for email message, notification for system "\
124                  "message, comment for other messages such as user replies"),
125         'email_from': fields.char('From',
126             help="Email address of the sender. This field is set when no matching partner is found for incoming emails."),
127         'reply_to': fields.char('Reply-To',
128             help='Reply email address. Setting the reply_to bypasses the automatic thread creation.'),
129         'no_auto_thread': fields.boolean('No threading for answers',
130             help='Answers do not go in the original document\' discussion thread. This has an impact on the generated message-id.'),
131         'author_id': fields.many2one('res.partner', 'Author', select=1,
132             ondelete='set null',
133             help="Author of the message. If not set, email_from may hold an email address that did not match any partner."),
134         'author_avatar': fields.related('author_id', 'image_small', type="binary", string="Author's Avatar"),
135         'partner_ids': fields.many2many('res.partner', string='Recipients'),
136         'notified_partner_ids': fields.many2many('res.partner', 'mail_notification',
137             'message_id', 'partner_id', 'Notified partners',
138             help='Partners that have a notification pushing this message in their mailboxes'),
139         'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel',
140             'message_id', 'attachment_id', 'Attachments'),
141         'parent_id': fields.many2one('mail.message', 'Parent Message', select=True,
142             ondelete='set null', help="Initial thread message."),
143         'child_ids': fields.one2many('mail.message', 'parent_id', 'Child Messages'),
144         'model': fields.char('Related Document Model', size=128, select=1),
145         'res_id': fields.integer('Related Document ID', select=1),
146         'record_name': fields.char('Message Record Name', help="Name get of the related document."),
147         'notification_ids': fields.one2many('mail.notification', 'message_id',
148             string='Notifications', auto_join=True,
149             help='Technical field holding the message notifications. Use notified_partner_ids to access notified partners.'),
150         'subject': fields.char('Subject'),
151         'date': fields.datetime('Date'),
152         'message_id': fields.char('Message-Id', help='Message unique identifier', select=1, readonly=1, copy=False),
153         'body': fields.html('Contents', help='Automatically sanitized HTML contents'),
154         'to_read': fields.function(_get_to_read, fnct_search=_search_to_read,
155             type='boolean', string='To read',
156             help='Current user has an unread notification linked to this message'),
157         'starred': fields.function(_get_starred, fnct_search=_search_starred,
158             type='boolean', string='Starred',
159             help='Current user has a starred notification linked to this message'),
160         'subtype_id': fields.many2one('mail.message.subtype', 'Subtype',
161             ondelete='set null', select=1,),
162         'vote_user_ids': fields.many2many('res.users', 'mail_vote',
163             'message_id', 'user_id', string='Votes',
164             help='Users that voted for this message'),
165         'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing mail server', readonly=1),
166     }
167
168     def _needaction_domain_get(self, cr, uid, context=None):
169         return [('to_read', '=', True)]
170
171     def _get_default_from(self, cr, uid, context=None):
172         this = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context)
173         if this.alias_name and this.alias_domain:
174             return formataddr((this.name, '%s@%s' % (this.alias_name, this.alias_domain)))
175         elif this.email:
176             return formataddr((this.name, this.email))
177         raise osv.except_osv(_('Invalid Action!'), _("Unable to send email, please configure the sender's email address or alias."))
178
179     def _get_default_author(self, cr, uid, context=None):
180         return self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id
181
182     _defaults = {
183         'type': 'email',
184         'date': fields.datetime.now,
185         'author_id': lambda self, cr, uid, ctx=None: self._get_default_author(cr, uid, ctx),
186         'body': '',
187         'email_from': lambda self, cr, uid, ctx=None: self._get_default_from(cr, uid, ctx),
188     }
189
190     #------------------------------------------------------
191     # Vote/Like
192     #------------------------------------------------------
193
194     def vote_toggle(self, cr, uid, ids, context=None):
195         ''' Toggles vote. Performed using read to avoid access rights issues.
196             Done as SUPERUSER_ID because uid may vote for a message he cannot modify. '''
197         for message in self.read(cr, uid, ids, ['vote_user_ids'], context=context):
198             new_has_voted = not (uid in message.get('vote_user_ids'))
199             if new_has_voted:
200                 self.write(cr, SUPERUSER_ID, message.get('id'), {'vote_user_ids': [(4, uid)]}, context=context)
201             else:
202                 self.write(cr, SUPERUSER_ID, message.get('id'), {'vote_user_ids': [(3, uid)]}, context=context)
203         return new_has_voted or False
204
205     #------------------------------------------------------
206     # download an attachment
207     #------------------------------------------------------
208
209     def download_attachment(self, cr, uid, id_message, attachment_id, context=None):
210         """ Return the content of linked attachments. """
211         # this will fail if you cannot read the message
212         message_values = self.read(cr, uid, [id_message], ['attachment_ids'], context=context)[0]
213         if attachment_id in message_values['attachment_ids']:
214             attachment = self.pool.get('ir.attachment').browse(cr, SUPERUSER_ID, attachment_id, context=context)
215             if attachment.datas and attachment.datas_fname:
216                 return {
217                     'base64': attachment.datas,
218                     'filename': attachment.datas_fname,
219                 }
220         return False
221
222     #------------------------------------------------------
223     # Notification API
224     #------------------------------------------------------
225
226     @api.cr_uid_ids_context
227     def set_message_read(self, cr, uid, msg_ids, read, create_missing=True, context=None):
228         """ Set messages as (un)read. Technically, the notifications related
229             to uid are set to (un)read. If for some msg_ids there are missing
230             notifications (i.e. due to load more or thread parent fetching),
231             they are created.
232
233             :param bool read: set notification as (un)read
234             :param bool create_missing: create notifications for missing entries
235                 (i.e. when acting on displayed messages not notified)
236
237             :return number of message mark as read
238         """
239         notification_obj = self.pool.get('mail.notification')
240         user_pid = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id
241         domain = [('partner_id', '=', user_pid), ('message_id', 'in', msg_ids)]
242         if not create_missing:
243             domain += [('is_read', '=', not read)]
244         notif_ids = notification_obj.search(cr, uid, domain, context=context)
245
246         # all message have notifications: already set them as (un)read
247         if len(notif_ids) == len(msg_ids) or not create_missing:
248             notification_obj.write(cr, uid, notif_ids, {'is_read': read}, context=context)
249             return len(notif_ids)
250
251         # some messages do not have notifications: find which one, create notification, update read status
252         notified_msg_ids = [notification.message_id.id for notification in notification_obj.browse(cr, uid, notif_ids, context=context)]
253         to_create_msg_ids = list(set(msg_ids) - set(notified_msg_ids))
254         for msg_id in to_create_msg_ids:
255             notification_obj.create(cr, uid, {'partner_id': user_pid, 'is_read': read, 'message_id': msg_id}, context=context)
256         notification_obj.write(cr, uid, notif_ids, {'is_read': read}, context=context)
257         return len(notif_ids)
258
259     @api.cr_uid_ids_context
260     def set_message_starred(self, cr, uid, msg_ids, starred, create_missing=True, context=None):
261         """ Set messages as (un)starred. Technically, the notifications related
262             to uid are set to (un)starred.
263
264             :param bool starred: set notification as (un)starred
265             :param bool create_missing: create notifications for missing entries
266                 (i.e. when acting on displayed messages not notified)
267         """
268         notification_obj = self.pool.get('mail.notification')
269         user_pid = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id
270         domain = [('partner_id', '=', user_pid), ('message_id', 'in', msg_ids)]
271         if not create_missing:
272             domain += [('starred', '=', not starred)]
273         values = {
274             'starred': starred
275         }
276         if starred:
277             values['is_read'] = False
278
279         notif_ids = notification_obj.search(cr, uid, domain, context=context)
280
281         # all message have notifications: already set them as (un)starred
282         if len(notif_ids) == len(msg_ids) or not create_missing:
283             notification_obj.write(cr, uid, notif_ids, values, context=context)
284             return starred
285
286         # some messages do not have notifications: find which one, create notification, update starred status
287         notified_msg_ids = [notification.message_id.id for notification in notification_obj.browse(cr, uid, notif_ids, context=context)]
288         to_create_msg_ids = list(set(msg_ids) - set(notified_msg_ids))
289         for msg_id in to_create_msg_ids:
290             notification_obj.create(cr, uid, dict(values, partner_id=user_pid, message_id=msg_id), context=context)
291         notification_obj.write(cr, uid, notif_ids, values, context=context)
292         return starred
293
294     #------------------------------------------------------
295     # Message loading for web interface
296     #------------------------------------------------------
297
298     def _message_read_dict_postprocess(self, cr, uid, messages, message_tree, context=None):
299         """ Post-processing on values given by message_read. This method will
300             handle partners in batch to avoid doing numerous queries.
301
302             :param list messages: list of message, as get_dict result
303             :param dict message_tree: {[msg.id]: msg browse record}
304         """
305         res_partner_obj = self.pool.get('res.partner')
306         ir_attachment_obj = self.pool.get('ir.attachment')
307         pid = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id
308
309         # 1. Aggregate partners (author_id and partner_ids) and attachments
310         partner_ids = set()
311         attachment_ids = set()
312         for key, message in message_tree.iteritems():
313             if message.author_id:
314                 partner_ids |= set([message.author_id.id])
315             if message.subtype_id and message.notified_partner_ids:  # take notified people of message with a subtype
316                 partner_ids |= set([partner.id for partner in message.notified_partner_ids])
317             elif not message.subtype_id and message.partner_ids:  # take specified people of message without a subtype (log)
318                 partner_ids |= set([partner.id for partner in message.partner_ids])
319             if message.attachment_ids:
320                 attachment_ids |= set([attachment.id for attachment in message.attachment_ids])
321         # Read partners as SUPERUSER -> display the names like classic m2o even if no access
322         partners = res_partner_obj.name_get(cr, SUPERUSER_ID, list(partner_ids), context=context)
323         partner_tree = dict((partner[0], partner) for partner in partners)
324
325         # 2. Attachments as SUPERUSER, because could receive msg and attachments for doc uid cannot see
326         attachments = ir_attachment_obj.read(cr, SUPERUSER_ID, list(attachment_ids), ['id', 'datas_fname', 'name', 'file_type_icon'], context=context)
327         attachments_tree = dict((attachment['id'], {
328             'id': attachment['id'],
329             'filename': attachment['datas_fname'],
330             'name': attachment['name'],
331             'file_type_icon': attachment['file_type_icon'],
332         }) for attachment in attachments)
333
334         # 3. Update message dictionaries
335         for message_dict in messages:
336             message_id = message_dict.get('id')
337             message = message_tree[message_id]
338             if message.author_id:
339                 author = partner_tree[message.author_id.id]
340             else:
341                 author = (0, message.email_from)
342             partner_ids = []
343             if message.subtype_id:
344                 partner_ids = [partner_tree[partner.id] for partner in message.notified_partner_ids
345                                 if partner.id in partner_tree]
346             else:
347                 partner_ids = [partner_tree[partner.id] for partner in message.partner_ids
348                                 if partner.id in partner_tree]
349             attachment_ids = []
350             for attachment in message.attachment_ids:
351                 if attachment.id in attachments_tree:
352                     attachment_ids.append(attachments_tree[attachment.id])
353             message_dict.update({
354                 'is_author': pid == author[0],
355                 'author_id': author,
356                 'partner_ids': partner_ids,
357                 'attachment_ids': attachment_ids,
358                 'user_pid': pid
359                 })
360         return True
361
362     def _message_read_dict(self, cr, uid, message, parent_id=False, context=None):
363         """ Return a dict representation of the message. This representation is
364             used in the JS client code, to display the messages. Partners and
365             attachments related stuff will be done in post-processing in batch.
366
367             :param dict message: mail.message browse record
368         """
369         # private message: no model, no res_id
370         is_private = False
371         if not message.model or not message.res_id:
372             is_private = True
373         # votes and favorites: res.users ids, no prefetching should be done
374         vote_nb = len(message.vote_user_ids)
375         has_voted = uid in [user.id for user in message.vote_user_ids]
376
377         try:
378             if parent_id:
379                 max_length = 300
380             else:
381                 max_length = 100
382             body_short = html_email_clean(message.body, remove=False, shorten=True, max_length=max_length)
383
384         except Exception:
385             body_short = '<p><b>Encoding Error : </b><br/>Unable to convert this message (id: %s).</p>' % message.id
386             _logger.exception(Exception)
387
388         return {'id': message.id,
389                 'type': message.type,
390                 'subtype': message.subtype_id.name if message.subtype_id else False,
391                 'body': message.body,
392                 'body_short': body_short,
393                 'model': message.model,
394                 'res_id': message.res_id,
395                 'record_name': message.record_name,
396                 'subject': message.subject,
397                 'date': message.date,
398                 'to_read': message.to_read,
399                 'parent_id': parent_id,
400                 'is_private': is_private,
401                 'author_id': False,
402                 'author_avatar': message.author_avatar,
403                 'is_author': False,
404                 'partner_ids': [],
405                 'vote_nb': vote_nb,
406                 'has_voted': has_voted,
407                 'is_favorite': message.starred,
408                 'attachment_ids': [],
409             }
410
411     def _message_read_add_expandables(self, cr, uid, messages, message_tree, parent_tree,
412             message_unload_ids=[], thread_level=0, domain=[], parent_id=False, context=None):
413         """ Create expandables for message_read, to load new messages.
414             1. get the expandable for new threads
415                 if display is flat (thread_level == 0):
416                     fetch message_ids < min(already displayed ids), because we
417                     want a flat display, ordered by id
418                 else:
419                     fetch message_ids that are not childs of already displayed
420                     messages
421             2. get the expandables for new messages inside threads if display
422                is not flat
423                 for each thread header, search for its childs
424                     for each hole in the child list based on message displayed,
425                     create an expandable
426
427             :param list messages: list of message structure for the Chatter
428                 widget to which expandables are added
429             :param dict message_tree: dict [id]: browse record of this message
430             :param dict parent_tree: dict [parent_id]: [child_ids]
431             :param list message_unload_ids: list of message_ids we do not want
432                 to load
433             :return bool: True
434         """
435         def _get_expandable(domain, message_nb, parent_id, max_limit):
436             return {
437                 'domain': domain,
438                 'nb_messages': message_nb,
439                 'type': 'expandable',
440                 'parent_id': parent_id,
441                 'max_limit':  max_limit,
442             }
443
444         if not messages:
445             return True
446         message_ids = sorted(message_tree.keys())
447
448         # 1. get the expandable for new threads
449         if thread_level == 0:
450             exp_domain = domain + [('id', '<', min(message_unload_ids + message_ids))]
451         else:
452             exp_domain = domain + ['!', ('id', 'child_of', message_unload_ids + parent_tree.keys())]
453         more_count = self.search_count(cr, uid, exp_domain, context=context)
454         if more_count:
455             # inside a thread: prepend
456             if parent_id:
457                 messages.insert(0, _get_expandable(exp_domain, -1, parent_id, True))
458             # new threads: append
459             else:
460                 messages.append(_get_expandable(exp_domain, -1, parent_id, True))
461
462         # 2. get the expandables for new messages inside threads if display is not flat
463         if thread_level == 0:
464             return True
465         for message_id in message_ids:
466             message = message_tree[message_id]
467
468             # generate only for thread header messages (TDE note: parent_id may be False is uid cannot see parent_id, seems ok)
469             if message.parent_id:
470                 continue
471
472             # check there are message for expandable
473             child_ids = set([child.id for child in message.child_ids]) - set(message_unload_ids)
474             child_ids = sorted(list(child_ids), reverse=True)
475             if not child_ids:
476                 continue
477
478             # make groups of unread messages
479             id_min, id_max, nb = max(child_ids), 0, 0
480             for child_id in child_ids:
481                 if not child_id in message_ids:
482                     nb += 1
483                     if id_min > child_id:
484                         id_min = child_id
485                     if id_max < child_id:
486                         id_max = child_id
487                 elif nb > 0:
488                     exp_domain = [('id', '>=', id_min), ('id', '<=', id_max), ('id', 'child_of', message_id)]
489                     idx = [msg.get('id') for msg in messages].index(child_id) + 1
490                     # messages.append(_get_expandable(exp_domain, nb, message_id, False))
491                     messages.insert(idx, _get_expandable(exp_domain, nb, message_id, False))
492                     id_min, id_max, nb = max(child_ids), 0, 0
493                 else:
494                     id_min, id_max, nb = max(child_ids), 0, 0
495             if nb > 0:
496                 exp_domain = [('id', '>=', id_min), ('id', '<=', id_max), ('id', 'child_of', message_id)]
497                 idx = [msg.get('id') for msg in messages].index(message_id) + 1
498                 # messages.append(_get_expandable(exp_domain, nb, message_id, id_min))
499                 messages.insert(idx, _get_expandable(exp_domain, nb, message_id, False))
500
501         return True
502
503     @api.cr_uid_context
504     def message_read(self, cr, uid, ids=None, domain=None, message_unload_ids=None,
505                         thread_level=0, context=None, parent_id=False, limit=None):
506         """ Read messages from mail.message, and get back a list of structured
507             messages to be displayed as discussion threads. If IDs is set,
508             fetch these records. Otherwise use the domain to fetch messages.
509             After having fetch messages, their ancestors will be added to obtain
510             well formed threads, if uid has access to them.
511
512             After reading the messages, expandable messages are added in the
513             message list (see ``_message_read_add_expandables``). It consists
514             in messages holding the 'read more' data: number of messages to
515             read, domain to apply.
516
517             :param list ids: optional IDs to fetch
518             :param list domain: optional domain for searching ids if ids not set
519             :param list message_unload_ids: optional ids we do not want to fetch,
520                 because i.e. they are already displayed somewhere
521             :param int parent_id: context of parent_id
522                 - if parent_id reached when adding ancestors, stop going further
523                   in the ancestor search
524                 - if set in flat mode, ancestor_id is set to parent_id
525             :param int limit: number of messages to fetch, before adding the
526                 ancestors and expandables
527             :return list: list of message structure for the Chatter widget
528         """
529         assert thread_level in [0, 1], 'message_read() thread_level should be 0 (flat) or 1 (1 level of thread); given %s.' % thread_level
530         domain = domain if domain is not None else []
531         message_unload_ids = message_unload_ids if message_unload_ids is not None else []
532         if message_unload_ids:
533             domain += [('id', 'not in', message_unload_ids)]
534         limit = limit or self._message_read_limit
535         message_tree = {}
536         message_list = []
537         parent_tree = {}
538
539         # no specific IDS given: fetch messages according to the domain, add their parents if uid has access to
540         if ids is None:
541             ids = self.search(cr, uid, domain, context=context, limit=limit)
542
543         # fetch parent if threaded, sort messages
544         for message in self.browse(cr, uid, ids, context=context):
545             message_id = message.id
546             if message_id in message_tree:
547                 continue
548             message_tree[message_id] = message
549
550             # find parent_id
551             if thread_level == 0:
552                 tree_parent_id = parent_id
553             else:
554                 tree_parent_id = message_id
555                 parent = message
556                 while parent.parent_id and parent.parent_id.id != parent_id:
557                     parent = parent.parent_id
558                     tree_parent_id = parent.id
559                 if not parent.id in message_tree:
560                     message_tree[parent.id] = parent
561             # newest messages first
562             parent_tree.setdefault(tree_parent_id, [])
563             if tree_parent_id != message_id:
564                 parent_tree[tree_parent_id].append(self._message_read_dict(cr, uid, message_tree[message_id], parent_id=tree_parent_id, context=context))
565
566         if thread_level:
567             for key, message_id_list in parent_tree.iteritems():
568                 message_id_list.sort(key=lambda item: item['id'])
569                 message_id_list.insert(0, self._message_read_dict(cr, uid, message_tree[key], context=context))
570
571         # create final ordered message_list based on parent_tree
572         parent_list = parent_tree.items()
573         parent_list = sorted(parent_list, key=lambda item: max([msg.get('id') for msg in item[1]]) if item[1] else item[0], reverse=True)
574         message_list = [message for (key, msg_list) in parent_list for message in msg_list]
575
576         # get the child expandable messages for the tree
577         self._message_read_dict_postprocess(cr, uid, message_list, message_tree, context=context)
578         self._message_read_add_expandables(cr, uid, message_list, message_tree, parent_tree,
579             thread_level=thread_level, message_unload_ids=message_unload_ids, domain=domain, parent_id=parent_id, context=context)
580         return message_list
581
582     def get_likers_list(self, cr, uid, ids, limit=10, context=None):
583         """ Return the people list who liked this message. """
584         voter_names = []
585         message = self.browse(cr, uid, ids, context=context)
586         for voter in message.vote_user_ids[:limit]:
587             voter_names.append(voter.name)
588         if len(message.vote_user_ids) > limit:
589             voter_names.append(_("and %s others like this") % (len(message.vote_user_ids) - limit))
590         return voter_names
591
592     #------------------------------------------------------
593     # mail_message internals
594     #------------------------------------------------------
595
596     def init(self, cr):
597         cr.execute("""SELECT indexname FROM pg_indexes WHERE indexname = 'mail_message_model_res_id_idx'""")
598         if not cr.fetchone():
599             cr.execute("""CREATE INDEX mail_message_model_res_id_idx ON mail_message (model, res_id)""")
600
601     def _find_allowed_model_wise(self, cr, uid, doc_model, doc_dict, context=None):
602         doc_ids = doc_dict.keys()
603         allowed_doc_ids = self.pool[doc_model].search(cr, uid, [('id', 'in', doc_ids)], context=context)
604         return set([message_id for allowed_doc_id in allowed_doc_ids for message_id in doc_dict[allowed_doc_id]])
605
606     def _find_allowed_doc_ids(self, cr, uid, model_ids, context=None):
607         model_access_obj = self.pool.get('ir.model.access')
608         allowed_ids = set()
609         for doc_model, doc_dict in model_ids.iteritems():
610             if not model_access_obj.check(cr, uid, doc_model, 'read', False):
611                 continue
612             allowed_ids |= self._find_allowed_model_wise(cr, uid, doc_model, doc_dict, context=context)
613         return allowed_ids
614
615     def _search(self, cr, uid, args, offset=0, limit=None, order=None,
616                 context=None, count=False, access_rights_uid=None):
617         """ Override that adds specific access rights of mail.message, to remove
618             ids uid could not see according to our custom rules. Please refer
619             to check_access_rule for more details about those rules.
620
621             After having received ids of a classic search, keep only:
622             - if author_id == pid, uid is the author, OR
623             - a notification (id, pid) exists, uid has been notified, OR
624             - uid have read access to the related document is model, res_id
625             - otherwise: remove the id
626         """
627         # Rules do not apply to administrator
628         if uid == SUPERUSER_ID:
629             return super(mail_message, self)._search(
630                 cr, uid, args, offset=offset, limit=limit, order=order,
631                 context=context, count=count, access_rights_uid=access_rights_uid)
632         # Perform a super with count as False, to have the ids, not a counter
633         ids = super(mail_message, self)._search(
634             cr, uid, args, offset=offset, limit=limit, order=order,
635             context=context, count=False, access_rights_uid=access_rights_uid)
636         if not ids and count:
637             return 0
638         elif not ids:
639             return ids
640
641         pid = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id
642         author_ids, partner_ids, allowed_ids = set([]), set([]), set([])
643         model_ids = {}
644
645         # check read access rights before checking the actual rules on the given ids
646         super(mail_message, self).check_access_rights(cr, access_rights_uid or uid, 'read')
647
648         cr.execute("""SELECT DISTINCT m.id, m.model, m.res_id, m.author_id, n.partner_id
649             FROM "%s" m LEFT JOIN "mail_notification" n
650             ON n.message_id=m.id AND n.partner_id = (%%s)
651             WHERE m.id = ANY (%%s)""" % self._table, (pid, ids,))
652         for id, rmod, rid, author_id, partner_id in cr.fetchall():
653             if author_id == pid:
654                 author_ids.add(id)
655             elif partner_id == pid:
656                 partner_ids.add(id)
657             elif rmod and rid:
658                 model_ids.setdefault(rmod, {}).setdefault(rid, set()).add(id)
659
660         allowed_ids = self._find_allowed_doc_ids(cr, uid, model_ids, context=context)
661         final_ids = author_ids | partner_ids | allowed_ids
662
663         if count:
664             return len(final_ids)
665         else:
666             # re-construct a list based on ids, because set did not keep the original order
667             id_list = [id for id in ids if id in final_ids]
668             return id_list
669
670     def check_access_rule(self, cr, uid, ids, operation, context=None):
671         """ Access rules of mail.message:
672             - read: if
673                 - author_id == pid, uid is the author, OR
674                 - mail_notification (id, pid) exists, uid has been notified, OR
675                 - uid have read access to the related document if model, res_id
676                 - otherwise: raise
677             - create: if
678                 - no model, no res_id, I create a private message OR
679                 - pid in message_follower_ids if model, res_id OR
680                 - mail_notification (parent_id.id, pid) exists, uid has been notified of the parent, OR
681                 - uid have write or create access on the related document if model, res_id, OR
682                 - otherwise: raise
683             - write: if
684                 - author_id == pid, uid is the author, OR
685                 - uid has write or create access on the related document if model, res_id
686                 - otherwise: raise
687             - unlink: if
688                 - uid has write or create access on the related document if model, res_id
689                 - otherwise: raise
690         """
691         def _generate_model_record_ids(msg_val, msg_ids):
692             """ :param model_record_ids: {'model': {'res_id': (msg_id, msg_id)}, ... }
693                 :param message_values: {'msg_id': {'model': .., 'res_id': .., 'author_id': ..}}
694             """
695             model_record_ids = {}
696             for id in msg_ids:
697                 vals = msg_val.get(id, {})
698                 if vals.get('model') and vals.get('res_id'):
699                     model_record_ids.setdefault(vals['model'], set()).add(vals['res_id'])
700             return model_record_ids
701
702         if uid == SUPERUSER_ID:
703             return
704         if isinstance(ids, (int, long)):
705             ids = [ids]
706         not_obj = self.pool.get('mail.notification')
707         fol_obj = self.pool.get('mail.followers')
708         partner_id = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=None).partner_id.id
709
710         # Read mail_message.ids to have their values
711         message_values = dict((res_id, {}) for res_id in ids)
712         cr.execute('SELECT DISTINCT id, model, res_id, author_id, parent_id FROM "%s" WHERE id = ANY (%%s)' % self._table, (ids,))
713         for id, rmod, rid, author_id, parent_id in cr.fetchall():
714             message_values[id] = {'model': rmod, 'res_id': rid, 'author_id': author_id, 'parent_id': parent_id}
715
716         # Author condition (READ, WRITE, CREATE (private)) -> could become an ir.rule ?
717         author_ids = []
718         if operation == 'read' or operation == 'write':
719             author_ids = [mid for mid, message in message_values.iteritems()
720                           if message.get('author_id') and message.get('author_id') == partner_id]
721         elif operation == 'create':
722             author_ids = [mid for mid, message in message_values.iteritems()
723                           if not message.get('model') and not message.get('res_id')]
724
725         # Parent condition, for create (check for received notifications for the created message parent)
726         notified_ids = []
727         if operation == 'create':
728             parent_ids = [message.get('parent_id') for mid, message in message_values.iteritems()
729                           if message.get('parent_id')]
730             not_ids = not_obj.search(cr, SUPERUSER_ID, [('message_id.id', 'in', parent_ids), ('partner_id', '=', partner_id)], context=context)
731             not_parent_ids = [notif.message_id.id for notif in not_obj.browse(cr, SUPERUSER_ID, not_ids, context=context)]
732             notified_ids += [mid for mid, message in message_values.iteritems()
733                              if message.get('parent_id') in not_parent_ids]
734
735         # Notification condition, for read (check for received notifications and create (in message_follower_ids)) -> could become an ir.rule, but not till we do not have a many2one variable field
736         other_ids = set(ids).difference(set(author_ids), set(notified_ids))
737         model_record_ids = _generate_model_record_ids(message_values, other_ids)
738         if operation == 'read':
739             not_ids = not_obj.search(cr, SUPERUSER_ID, [
740                 ('partner_id', '=', partner_id),
741                 ('message_id', 'in', ids),
742             ], context=context)
743             notified_ids = [notification.message_id.id for notification in not_obj.browse(cr, SUPERUSER_ID, not_ids, context=context)]
744         elif operation == 'create':
745             for doc_model, doc_ids in model_record_ids.items():
746                 fol_ids = fol_obj.search(cr, SUPERUSER_ID, [
747                     ('res_model', '=', doc_model),
748                     ('res_id', 'in', list(doc_ids)),
749                     ('partner_id', '=', partner_id),
750                 ], context=context)
751                 fol_mids = [follower.res_id for follower in fol_obj.browse(cr, SUPERUSER_ID, fol_ids, context=context)]
752                 notified_ids += [mid for mid, message in message_values.iteritems()
753                                  if message.get('model') == doc_model and message.get('res_id') in fol_mids]
754
755         # CRUD: Access rights related to the document
756         other_ids = other_ids.difference(set(notified_ids))
757         model_record_ids = _generate_model_record_ids(message_values, other_ids)
758         document_related_ids = []
759         for model, doc_ids in model_record_ids.items():
760             model_obj = self.pool[model]
761             mids = model_obj.exists(cr, uid, list(doc_ids))
762             if hasattr(model_obj, 'check_mail_message_access'):
763                 model_obj.check_mail_message_access(cr, uid, mids, operation, context=context)
764             else:
765                 self.pool['mail.thread'].check_mail_message_access(cr, uid, mids, operation, model_obj=model_obj, context=context)
766             document_related_ids += [mid for mid, message in message_values.iteritems()
767                                      if message.get('model') == model and message.get('res_id') in mids]
768
769         # Calculate remaining ids: if not void, raise an error
770         other_ids = other_ids.difference(set(document_related_ids))
771         if not other_ids:
772             return
773         raise orm.except_orm(_('Access Denied'),
774                              _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') %
775                              (self._description, operation))
776
777     def _get_record_name(self, cr, uid, values, context=None):
778         """ Return the related document name, using name_get. It is done using
779             SUPERUSER_ID, to be sure to have the record name correctly stored. """
780         if not values.get('model') or not values.get('res_id') or values['model'] not in self.pool:
781             return False
782         return self.pool[values['model']].name_get(cr, SUPERUSER_ID, [values['res_id']], context=context)[0][1]
783
784     def _get_reply_to(self, cr, uid, values, context=None):
785         """ Return a specific reply_to: alias of the document through message_get_reply_to
786             or take the email_from
787         """
788         model, res_id, email_from = values.get('model'), values.get('res_id'), values.get('email_from')
789         ctx = dict(context, thread_model=model)
790         return self.pool['mail.thread'].message_get_reply_to(cr, uid, [res_id], default=email_from, context=ctx)[res_id]
791
792     def _get_message_id(self, cr, uid, values, context=None):
793         if values.get('no_auto_thread', False) is True:
794             message_id = tools.generate_tracking_message_id('reply_to')
795         elif values.get('res_id') and values.get('model'):
796             message_id = tools.generate_tracking_message_id('%(res_id)s-%(model)s' % values)
797         else:
798             message_id = tools.generate_tracking_message_id('private')
799         return message_id
800
801     def create(self, cr, uid, values, context=None):
802         context = dict(context or {})
803         default_starred = context.pop('default_starred', False)
804
805         if 'email_from' not in values:  # needed to compute reply_to
806             values['email_from'] = self._get_default_from(cr, uid, context=context)
807         if not values.get('message_id'):
808             values['message_id'] = self._get_message_id(cr, uid, values, context=context)
809         if 'reply_to' not in values:
810             values['reply_to'] = self._get_reply_to(cr, uid, values, context=context)
811         if 'record_name' not in values and 'default_record_name' not in context:
812             values['record_name'] = self._get_record_name(cr, uid, values, context=context)
813
814         newid = super(mail_message, self).create(cr, uid, values, context)
815
816         self._notify(cr, uid, newid, context=context,
817                      force_send=context.get('mail_notify_force_send', True),
818                      user_signature=context.get('mail_notify_user_signature', True))
819         # TDE FIXME: handle default_starred. Why not setting an inv on starred ?
820         # Because starred will call set_message_starred, that looks for notifications.
821         # When creating a new mail_message, it will create a notification to a message
822         # that does not exist, leading to an error (key not existing). Also this
823         # this means unread notifications will be created, yet we can not assure
824         # this is what we want.
825         if default_starred:
826             self.set_message_starred(cr, uid, [newid], True, context=context)
827         return newid
828
829     def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
830         """ Override to explicitely call check_access_rule, that is not called
831             by the ORM. It instead directly fetches ir.rules and apply them. """
832         self.check_access_rule(cr, uid, ids, 'read', context=context)
833         res = super(mail_message, self).read(cr, uid, ids, fields=fields, context=context, load=load)
834         return res
835
836     def unlink(self, cr, uid, ids, context=None):
837         # cascade-delete attachments that are directly attached to the message (should only happen
838         # for mail.messages that act as parent for a standalone mail.mail record).
839         self.check_access_rule(cr, uid, ids, 'unlink', context=context)
840         attachments_to_delete = []
841         for message in self.browse(cr, uid, ids, context=context):
842             for attach in message.attachment_ids:
843                 if attach.res_model == self._name and (attach.res_id == message.id or attach.res_id == 0):
844                     attachments_to_delete.append(attach.id)
845         if attachments_to_delete:
846             self.pool.get('ir.attachment').unlink(cr, uid, attachments_to_delete, context=context)
847         return super(mail_message, self).unlink(cr, uid, ids, context=context)
848
849     #------------------------------------------------------
850     # Messaging API
851     #------------------------------------------------------
852
853     def _notify(self, cr, uid, newid, context=None, force_send=False, user_signature=True):
854         """ Add the related record followers to the destination partner_ids if is not a private message.
855             Call mail_notification.notify to manage the email sending
856         """
857         notification_obj = self.pool.get('mail.notification')
858         message = self.browse(cr, uid, newid, context=context)
859         partners_to_notify = set([])
860
861         # all followers of the mail.message document have to be added as partners and notified if a subtype is defined (otherwise: log message)
862         if message.subtype_id and message.model and message.res_id:
863             fol_obj = self.pool.get("mail.followers")
864             # browse as SUPERUSER because rules could restrict the search results
865             fol_ids = fol_obj.search(
866                 cr, SUPERUSER_ID, [
867                     ('res_model', '=', message.model),
868                     ('res_id', '=', message.res_id),
869                 ], context=context)
870             partners_to_notify |= set(
871                 fo.partner_id.id for fo in fol_obj.browse(cr, SUPERUSER_ID, fol_ids, context=context)
872                 if message.subtype_id.id in [st.id for st in fo.subtype_ids]
873             )
874         # remove me from notified partners, unless the message is written on my own wall
875         if message.subtype_id and message.author_id and message.model == "res.partner" and message.res_id == message.author_id.id:
876             partners_to_notify |= set([message.author_id.id])
877         elif message.author_id:
878             partners_to_notify -= set([message.author_id.id])
879
880         # all partner_ids of the mail.message have to be notified regardless of the above (even the author if explicitly added!)
881         if message.partner_ids:
882             partners_to_notify |= set([p.id for p in message.partner_ids])
883
884         # notify
885         notification_obj._notify(
886             cr, uid, newid, partners_to_notify=list(partners_to_notify), context=context,
887             force_send=force_send, user_signature=user_signature
888         )
889         message.refresh()
890
891         # An error appear when a user receive a notification without notifying
892         # the parent message -> add a read notification for the parent
893         if message.parent_id:
894             # all notified_partner_ids of the mail.message have to be notified for the parented messages
895             partners_to_parent_notify = set(message.notified_partner_ids).difference(message.parent_id.notified_partner_ids)
896             for partner in partners_to_parent_notify:
897                 notification_obj.create(cr, uid, {
898                         'message_id': message.parent_id.id,
899                         'partner_id': partner.id,
900                         'is_read': True,
901                     }, context=context)