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