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