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