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