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