1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>)
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
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
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/>
20 ##############################################################################
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 _
31 _logger = logging.getLogger(__name__)
34 from mako.template import Template as MakoTemplate
36 _logger.warning("payment_acquirer: mako templates not available, payment acquirer will not work!")
39 """ Some tools for parsing / creating email fields """
41 """Returns unicode() string conversion of the the given encoded smtp header text"""
43 text = decode_header(text.replace('\r', ''))
44 return ''.join([tools.ustr(x[0], x[1]) for x in text])
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']
54 _rec_name = 'record_name'
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
62 def _shorten_name(self, name):
63 if len(name) <= (self._message_record_name_length + 3):
65 return name[:self._message_record_name_length] + '...'
67 def _get_record_name(self, cr, uid, ids, name, arg, context=None):
68 """ Return the related document name, using name_get. It is done using
69 SUPERUSER_ID, to be sure to have the record name correctly stored. """
70 # TDE note: regroup by model/ids, to have less queries to perform
71 result = dict.fromkeys(ids, False)
72 for message in self.read(cr, uid, ids, ['model', 'res_id'], context=context):
73 if not message.get('model') or not message.get('res_id'):
75 result[message['id']] = self._shorten_name(self.pool.get(message['model']).name_get(cr, SUPERUSER_ID, [message['res_id']], context=context)[0][1])
78 def _get_to_read(self, cr, uid, ids, name, arg, context=None):
79 """ Compute if the message is unread by the current user. """
80 res = dict((id, False) for id in ids)
81 partner_id = self.pool.get('res.users').read(cr, uid, uid, ['partner_id'], context=context)['partner_id'][0]
82 notif_obj = self.pool.get('mail.notification')
83 notif_ids = notif_obj.search(cr, uid, [
84 ('partner_id', 'in', [partner_id]),
85 ('message_id', 'in', ids),
88 for notif in notif_obj.browse(cr, uid, notif_ids, context=context):
89 res[notif.message_id.id] = True
92 def _search_to_read(self, cr, uid, obj, name, domain, context=None):
93 """ Search for messages to read by the current user. Condition is
94 inversed because we search unread message on a read column. """
96 read_cond = "(read = False OR read IS NULL)"
98 read_cond = "read = True"
99 partner_id = self.pool.get('res.users').read(cr, uid, uid, ['partner_id'], context=context)['partner_id'][0]
100 cr.execute("SELECT message_id FROM mail_notification "\
101 "WHERE partner_id = %%s AND %s" % read_cond,
103 return [('id', 'in', [r[0] for r in cr.fetchall()])]
105 def name_get(self, cr, uid, ids, context=None):
106 # name_get may receive int id instead of an id list
107 if isinstance(ids, (int, long)):
110 for message in self.browse(cr, uid, ids, context=context):
111 name = '%s: %s' % (message.subject or '', message.body or '')
112 res.append((message.id, self._shorten_name(name.lstrip(' :'))))
116 'type': fields.selection([
118 ('comment', 'Comment'),
119 ('notification', 'System notification'),
121 help="Message type: email for email message, notification for system "\
122 "message, comment for other messages such as user replies"),
123 'email_from': fields.char('From',
124 help="Email address of the sender. This field is set when no matching partner is found for incoming emails."),
125 'author_id': fields.many2one('res.partner', 'Author', select=1,
127 help="Author of the message. If not set, email_from may hold an email address that did not match any partner."),
128 'partner_ids': fields.many2many('res.partner', string='Recipients'),
129 'notified_partner_ids': fields.many2many('res.partner', 'mail_notification',
130 'message_id', 'partner_id', 'Notified partners',
131 help='Partners that have a notification pushing this message in their mailboxes'),
132 'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel',
133 'message_id', 'attachment_id', 'Attachments'),
134 'parent_id': fields.many2one('mail.message', 'Parent Message', select=True,
135 ondelete='set null', help="Initial thread message."),
136 'child_ids': fields.one2many('mail.message', 'parent_id', 'Child Messages'),
137 'model': fields.char('Related Document Model', size=128, select=1),
138 'res_id': fields.integer('Related Document ID', select=1),
139 'record_name': fields.function(_get_record_name, type='char',
140 store=True, string='Message Record Name',
141 help="Name get of the related document."),
142 'notification_ids': fields.one2many('mail.notification', 'message_id',
143 string='Notifications',
144 help='Technical field holding the message notifications. Use notified_partner_ids to access notified partners.'),
145 'subject': fields.char('Subject'),
146 'date': fields.datetime('Date'),
147 'message_id': fields.char('Message-Id', help='Message unique identifier', select=1, readonly=1),
148 'body': fields.html('Contents', help='Automatically sanitized HTML contents'),
149 'to_read': fields.function(_get_to_read, fnct_search=_search_to_read,
150 type='boolean', string='To read',
151 help='Functional field to search for messages the current user has to read'),
152 'subtype_id': fields.many2one('mail.message.subtype', 'Subtype',
153 ondelete='set null', select=1,),
154 'vote_user_ids': fields.many2many('res.users', 'mail_vote',
155 'message_id', 'user_id', string='Votes',
156 help='Users that voted for this message'),
157 'favorite_user_ids': fields.many2many('res.users', 'mail_favorite',
158 'message_id', 'user_id', string='Favorite',
159 help='Users that set this message in their favorites'),
162 def _needaction_domain_get(self, cr, uid, context=None):
164 return [('to_read', '=', True)]
167 def _get_default_author(self, cr, uid, context=None):
168 return self.pool.get('res.users').read(cr, uid, uid, ['partner_id'], context=context)['partner_id'][0]
172 'date': lambda *a: fields.datetime.now(),
173 'author_id': lambda self, cr, uid, ctx={}: self._get_default_author(cr, uid, ctx),
177 #------------------------------------------------------
179 #------------------------------------------------------
181 def vote_toggle(self, cr, uid, ids, context=None):
182 ''' Toggles vote. Performed using read to avoid access rights issues.
183 Done as SUPERUSER_ID because uid may vote for a message he cannot modify. '''
184 for message in self.read(cr, uid, ids, ['vote_user_ids'], context=context):
185 new_has_voted = not (uid in message.get('vote_user_ids'))
187 self.write(cr, SUPERUSER_ID, message.get('id'), {'vote_user_ids': [(4, uid)]}, context=context)
189 self.write(cr, SUPERUSER_ID, message.get('id'), {'vote_user_ids': [(3, uid)]}, context=context)
190 return new_has_voted or False
192 #------------------------------------------------------
194 #------------------------------------------------------
196 def favorite_toggle(self, cr, uid, ids, context=None):
197 ''' Toggles favorite. Performed using read to avoid access rights issues.
198 Done as SUPERUSER_ID because uid may star a message he cannot modify. '''
199 for message in self.read(cr, uid, ids, ['favorite_user_ids'], context=context):
200 new_is_favorite = not (uid in message.get('favorite_user_ids'))
202 self.write(cr, SUPERUSER_ID, message.get('id'), {'favorite_user_ids': [(4, uid)]}, context=context)
204 self.write(cr, SUPERUSER_ID, message.get('id'), {'favorite_user_ids': [(3, uid)]}, context=context)
205 return new_is_favorite or False
207 #------------------------------------------------------
208 # Message loading for web interface
209 #------------------------------------------------------
211 def _message_read_dict_postprocess(self, cr, uid, messages, message_tree, context=None):
212 """ Post-processing on values given by message_read. This method will
213 handle partners in batch to avoid doing numerous queries.
215 :param list messages: list of message, as get_dict result
216 :param dict message_tree: {[msg.id]: msg browse record}
218 res_partner_obj = self.pool.get('res.partner')
219 ir_attachment_obj = self.pool.get('ir.attachment')
220 pid = self.pool.get('res.users').read(cr, uid, uid, ['partner_id'], context=None)['partner_id'][0]
222 # 1. Aggregate partners (author_id and partner_ids) and attachments
224 attachment_ids = set()
225 for key, message in message_tree.iteritems():
226 if message.author_id:
227 partner_ids |= set([message.author_id.id])
228 if message.partner_ids:
229 partner_ids |= set([partner.id for partner in message.partner_ids])
230 if message.attachment_ids:
231 attachment_ids |= set([attachment.id for attachment in message.attachment_ids])
233 # Filter author_ids uid can see
234 # partner_ids = self.pool.get('res.partner').search(cr, uid, [('id', 'in', partner_ids)], context=context)
235 partners = res_partner_obj.name_get(cr, uid, list(partner_ids), context=context)
236 partner_tree = dict((partner[0], partner) for partner in partners)
239 attachments = ir_attachment_obj.read(cr, uid, list(attachment_ids), ['id', 'datas_fname'], context=context)
240 attachments_tree = dict((attachment['id'], {'id': attachment['id'], 'filename': attachment['datas_fname']}) for attachment in attachments)
242 # 3. Update message dictionaries
243 for message_dict in messages:
244 message_id = message_dict.get('id')
245 message = message_tree[message_id]
246 if message.author_id:
247 author = partner_tree[message.author_id.id]
249 author = (0, message.email_from)
251 for partner in message.partner_ids:
252 if partner.id in partner_tree:
253 partner_ids.append(partner_tree[partner.id])
255 for attachment in message.attachment_ids:
256 if attachment.id in attachments_tree:
257 attachment_ids.append(attachments_tree[attachment.id])
258 message_dict.update({
259 'is_author': pid == author[0],
261 'partner_ids': partner_ids,
262 'attachment_ids': attachment_ids,
266 def _message_read_dict(self, cr, uid, message, parent_id=False, context=None):
267 """ Return a dict representation of the message. This representation is
268 used in the JS client code, to display the messages. Partners and
269 attachments related stuff will be done in post-processing in batch.
271 :param dict message: mail.message browse record
273 # private message: no model, no res_id
275 if not message.model or not message.res_id:
277 # votes and favorites: res.users ids, no prefetching should be done
278 vote_nb = len(message.vote_user_ids)
279 has_voted = uid in [user.id for user in message.vote_user_ids]
280 is_favorite = uid in [user.id for user in message.favorite_user_ids]
282 return {'id': message.id,
283 'type': message.type,
284 'body': html_email_clean(message.body),
285 'model': message.model,
286 'res_id': message.res_id,
287 'record_name': message.record_name,
288 'subject': message.subject,
289 'date': message.date,
290 'to_read': message.to_read,
291 'parent_id': parent_id,
292 'is_private': is_private,
297 'has_voted': has_voted,
298 'is_favorite': is_favorite,
299 'attachment_ids': [],
302 def _message_read_add_expandables(self, cr, uid, messages, message_tree, parent_tree,
303 message_unload_ids=[], thread_level=0, domain=[], parent_id=False, context=None):
304 """ Create expandables for message_read, to load new messages.
305 1. get the expandable for new threads
306 if display is flat (thread_level == 0):
307 fetch message_ids < min(already displayed ids), because we
308 want a flat display, ordered by id
310 fetch message_ids that are not childs of already displayed
312 2. get the expandables for new messages inside threads if display
314 for each thread header, search for its childs
315 for each hole in the child list based on message displayed,
318 :param list messages: list of message structure for the Chatter
319 widget to which expandables are added
320 :param dict message_tree: dict [id]: browse record of this message
321 :param dict parent_tree: dict [parent_id]: [child_ids]
322 :param list message_unload_ids: list of message_ids we do not want
326 def _get_expandable(domain, message_nb, parent_id, max_limit):
329 'nb_messages': message_nb,
330 'type': 'expandable',
331 'parent_id': parent_id,
332 'max_limit': max_limit,
337 message_ids = sorted(message_tree.keys())
339 # 1. get the expandable for new threads
340 if thread_level == 0:
341 exp_domain = domain + [('id', '<', min(message_unload_ids + message_ids))]
343 exp_domain = domain + ['!', ('id', 'child_of', message_unload_ids + parent_tree.keys())]
344 ids = self.search(cr, uid, exp_domain, context=context, limit=1)
346 # inside a thread: prepend
348 messages.insert(0, _get_expandable(exp_domain, -1, parent_id, True))
349 # new threads: append
351 messages.append(_get_expandable(exp_domain, -1, parent_id, True))
353 # 2. get the expandables for new messages inside threads if display is not flat
354 if thread_level == 0:
356 for message_id in message_ids:
357 message = message_tree[message_id]
359 # generate only for thread header messages (TDE note: parent_id may be False is uid cannot see parent_id, seems ok)
360 if message.parent_id:
363 # check there are message for expandable
364 child_ids = set([child.id for child in message.child_ids]) - set(message_unload_ids)
365 child_ids = sorted(list(child_ids), reverse=True)
369 # make groups of unread messages
370 id_min, id_max, nb = max(child_ids), 0, 0
371 for child_id in child_ids:
372 if not child_id in message_ids:
374 if id_min > child_id:
376 if id_max < child_id:
379 exp_domain = [('id', '>=', id_min), ('id', '<=', id_max), ('id', 'child_of', message_id)]
380 messages.append(_get_expandable(exp_domain, nb, message_id, False))
381 id_min, id_max, nb = max(child_ids), 0, 0
383 id_min, id_max, nb = max(child_ids), 0, 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(message_id) + 1
387 # messages.append(_get_expandable(exp_domain, nb, message_id, id_min))
388 messages.insert(idx, _get_expandable(exp_domain, nb, message_id, False))
392 def message_read(self, cr, uid, ids=None, domain=None, message_unload_ids=None,
393 thread_level=0, context=None, parent_id=False, limit=None):
394 """ Read messages from mail.message, and get back a list of structured
395 messages to be displayed as discussion threads. If IDs is set,
396 fetch these records. Otherwise use the domain to fetch messages.
397 After having fetch messages, their ancestors will be added to obtain
398 well formed threads, if uid has access to them.
400 After reading the messages, expandable messages are added in the
401 message list (see ``_message_read_add_expandables``). It consists
402 in messages holding the 'read more' data: number of messages to
403 read, domain to apply.
405 :param list ids: optional IDs to fetch
406 :param list domain: optional domain for searching ids if ids not set
407 :param list message_unload_ids: optional ids we do not want to fetch,
408 because i.e. they are already displayed somewhere
409 :param int parent_id: context of parent_id
410 - if parent_id reached when adding ancestors, stop going further
411 in the ancestor search
412 - if set in flat mode, ancestor_id is set to parent_id
413 :param int limit: number of messages to fetch, before adding the
414 ancestors and expandables
415 :return list: list of message structure for the Chatter widget
417 assert thread_level in [0, 1], 'message_read() thread_level should be 0 (flat) or 1 (1 level of thread); given %s.' % thread_level
418 domain = domain if domain is not None else []
419 message_unload_ids = message_unload_ids if message_unload_ids is not None else []
420 if message_unload_ids:
421 domain += [('id', 'not in', message_unload_ids)]
422 limit = limit or self._message_read_limit
427 # no specific IDS given: fetch messages according to the domain, add their parents if uid has access to
429 ids = self.search(cr, uid, domain, context=context, limit=limit)
431 # fetch parent if threaded, sort messages
432 for message in self.browse(cr, uid, ids, context=context):
433 message_id = message.id
434 if message_id in message_tree:
436 message_tree[message_id] = message
439 if thread_level == 0:
440 tree_parent_id = parent_id
442 tree_parent_id = message_id
444 while parent.parent_id and parent.parent_id.id != parent_id:
445 parent = parent.parent_id
446 tree_parent_id = parent.id
447 if not parent.id in message_tree:
448 message_tree[parent.id] = parent
449 # newest messages first
450 parent_tree.setdefault(tree_parent_id, [])
451 if tree_parent_id != message_id:
452 parent_tree[tree_parent_id].append(self._message_read_dict(cr, uid, message_tree[message_id], parent_id=tree_parent_id, context=context))
455 for key, message_id_list in parent_tree.iteritems():
456 message_id_list.sort(key=lambda item: item['id'])
457 message_id_list.insert(0, self._message_read_dict(cr, uid, message_tree[key], context=context))
459 parent_list = parent_tree.items()
460 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)
461 message_list = [message for (key, msg_list) in parent_list for message in msg_list]
463 # get the child expandable messages for the tree
464 self._message_read_dict_postprocess(cr, uid, message_list, message_tree, context=context)
465 self._message_read_add_expandables(cr, uid, message_list, message_tree, parent_tree,
466 thread_level=thread_level, message_unload_ids=message_unload_ids, domain=domain, parent_id=parent_id, context=context)
469 # TDE Note: do we need this ?
470 # def user_free_attachment(self, cr, uid, context=None):
471 # attachment = self.pool.get('ir.attachment')
472 # attachment_list = []
473 # attachment_ids = attachment.search(cr, uid, [('res_model', '=', 'mail.message'), ('create_uid', '=', uid)])
474 # if len(attachment_ids):
475 # attachment_list = [{'id': attach.id, 'name': attach.name, 'date': attach.create_date} for attach in attachment.browse(cr, uid, attachment_ids, context=context)]
476 # return attachment_list
478 #------------------------------------------------------
479 # mail_message internals
480 #------------------------------------------------------
483 cr.execute("""SELECT indexname FROM pg_indexes WHERE indexname = 'mail_message_model_res_id_idx'""")
484 if not cr.fetchone():
485 cr.execute("""CREATE INDEX mail_message_model_res_id_idx ON mail_message (model, res_id)""")
487 def _search(self, cr, uid, args, offset=0, limit=None, order=None,
488 context=None, count=False, access_rights_uid=None):
489 """ Override that adds specific access rights of mail.message, to remove
490 ids uid could not see according to our custom rules. Please refer
491 to check_access_rule for more details about those rules.
493 After having received ids of a classic search, keep only:
494 - if author_id == pid, uid is the author, OR
495 - a notification (id, pid) exists, uid has been notified, OR
496 - uid have read access to the related document is model, res_id
497 - otherwise: remove the id
499 # Rules do not apply to administrator
500 if uid == SUPERUSER_ID:
501 return super(mail_message, self)._search(cr, uid, args, offset=offset, limit=limit, order=order,
502 context=context, count=count, access_rights_uid=access_rights_uid)
503 # Perform a super with count as False, to have the ids, not a counter
504 ids = super(mail_message, self)._search(cr, uid, args, offset=offset, limit=limit, order=order,
505 context=context, count=False, access_rights_uid=access_rights_uid)
506 if not ids and count:
511 pid = self.pool.get('res.users').read(cr, uid, uid, ['partner_id'])['partner_id'][0]
512 author_ids, partner_ids, allowed_ids = set([]), set([]), set([])
515 messages = super(mail_message, self).read(cr, uid, ids, ['author_id', 'model', 'res_id', 'notified_partner_ids'], context=context)
516 for message in messages:
517 if message.get('author_id') and message.get('author_id')[0] == pid:
518 author_ids.add(message.get('id'))
519 elif pid in message.get('notified_partner_ids'):
520 partner_ids.add(message.get('id'))
521 elif message.get('model') and message.get('res_id'):
522 model_ids.setdefault(message.get('model'), {}).setdefault(message.get('res_id'), set()).add(message.get('id'))
524 model_access_obj = self.pool.get('ir.model.access')
525 for doc_model, doc_dict in model_ids.iteritems():
526 if not model_access_obj.check(cr, uid, doc_model, 'read', False):
528 doc_ids = doc_dict.keys()
529 allowed_doc_ids = self.pool.get(doc_model).search(cr, uid, [('id', 'in', doc_ids)], context=context)
530 allowed_ids |= set([message_id for allowed_doc_id in allowed_doc_ids for message_id in doc_dict[allowed_doc_id]])
532 final_ids = author_ids | partner_ids | allowed_ids
534 return len(final_ids)
536 return list(final_ids)
538 def check_access_rule(self, cr, uid, ids, operation, context=None):
539 """ Access rules of mail.message:
541 - author_id == pid, uid is the author, OR
542 - mail_notification (id, pid) exists, uid has been notified, OR
543 - uid have read access to the related document if model, res_id
546 - no model, no res_id, I create a private message
547 - pid in message_follower_ids if model, res_id OR
548 - uid have write access on the related document if model, res_id, OR
551 - uid has write access on the related document if model, res_id
554 - uid has write access on the related document if model, res_id
557 if uid == SUPERUSER_ID:
559 if isinstance(ids, (int, long)):
561 partner_id = self.pool.get('res.users').read(cr, uid, uid, ['partner_id'], context=None)['partner_id'][0]
563 # Read mail_message.ids to have their values
564 message_values = dict.fromkeys(ids)
565 model_record_ids = {}
566 cr.execute('SELECT DISTINCT id, model, res_id, author_id FROM "%s" WHERE id = ANY (%%s)' % self._table, (ids,))
567 for id, rmod, rid, author_id in cr.fetchall():
568 message_values[id] = {'res_model': rmod, 'res_id': rid, 'author_id': author_id}
570 model_record_ids.setdefault(rmod, dict()).setdefault(rid, set()).add(id)
572 # Author condition, for read and create (private message) -> could become an ir.rule, but not till we do not have a many2one variable field
573 if operation == 'read':
574 author_ids = [mid for mid, message in message_values.iteritems()
575 if message.get('author_id') and message.get('author_id') == partner_id]
576 elif operation == 'create':
577 author_ids = [mid for mid, message in message_values.iteritems()
578 if not message.get('model') and not message.get('res_id')]
582 # 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
583 if operation == 'read':
584 not_obj = self.pool.get('mail.notification')
585 not_ids = not_obj.search(cr, SUPERUSER_ID, [
586 ('partner_id', '=', partner_id),
587 ('message_id', 'in', ids),
589 notified_ids = [notification.message_id.id for notification in not_obj.browse(cr, SUPERUSER_ID, not_ids, context=context)]
590 elif operation == 'create':
592 for doc_model, doc_dict in model_record_ids.items():
593 fol_obj = self.pool.get('mail.followers')
594 fol_ids = fol_obj.search(cr, SUPERUSER_ID, [
595 ('res_model', '=', doc_model),
596 ('res_id', 'in', list(doc_dict.keys())),
597 ('partner_id', '=', partner_id),
599 fol_mids = [follower.res_id for follower in fol_obj.browse(cr, SUPERUSER_ID, fol_ids, context=context)]
600 notified_ids += [mid for mid, message in message_values.iteritems()
601 if message.get('res_model') == doc_model and message.get('res_id') in fol_mids]
605 # Calculate remaining ids, and related model/res_ids
606 model_record_ids = {}
607 other_ids = set(ids).difference(set(author_ids), set(notified_ids))
609 if message_values[id]['res_model']:
610 model_record_ids.setdefault(message_values[id]['res_model'], set()).add(message_values[id]['res_id'])
612 # CRUD: Access rights related to the document
613 document_related_ids = []
614 for model, mids in model_record_ids.items():
615 model_obj = self.pool.get(model)
616 mids = model_obj.exists(cr, uid, mids)
617 if operation in ['create', 'write', 'unlink']:
618 model_obj.check_access_rights(cr, uid, 'write')
619 model_obj.check_access_rule(cr, uid, mids, 'write', context=context)
621 model_obj.check_access_rights(cr, uid, operation)
622 model_obj.check_access_rule(cr, uid, mids, operation, context=context)
623 document_related_ids += [mid for mid, message in message_values.iteritems()
624 if message.get('res_model') == model and message.get('res_id') in mids]
626 # Calculate remaining ids: if not void, raise an error
627 other_ids = other_ids - set(document_related_ids)
630 raise orm.except_orm(_('Access Denied'),
631 _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % \
632 (self._description, operation))
634 def create(self, cr, uid, values, context=None):
635 if not values.get('message_id') and values.get('res_id') and values.get('model'):
636 values['message_id'] = tools.generate_tracking_message_id('%(res_id)s-%(model)s' % values)
637 elif not values.get('message_id'):
638 values['message_id'] = tools.generate_tracking_message_id('private')
639 newid = super(mail_message, self).create(cr, uid, values, context)
640 self._notify(cr, SUPERUSER_ID, newid, context=context)
643 def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'):
644 """ Override to explicitely call check_access_rule, that is not called
645 by the ORM. It instead directly fetches ir.rules and apply them. """
646 self.check_access_rule(cr, uid, ids, 'read', context=context)
647 res = super(mail_message, self).read(cr, uid, ids, fields=fields, context=context, load=load)
650 def unlink(self, cr, uid, ids, context=None):
651 # cascade-delete attachments that are directly attached to the message (should only happen
652 # for mail.messages that act as parent for a standalone mail.mail record).
653 self.check_access_rule(cr, uid, ids, 'unlink', context=context)
654 attachments_to_delete = []
655 for message in self.browse(cr, uid, ids, context=context):
656 for attach in message.attachment_ids:
657 if attach.res_model == self._name and attach.res_id == message.id:
658 attachments_to_delete.append(attach.id)
659 if attachments_to_delete:
660 self.pool.get('ir.attachment').unlink(cr, uid, attachments_to_delete, context=context)
661 return super(mail_message, self).unlink(cr, uid, ids, context=context)
663 def copy(self, cr, uid, id, default=None, context=None):
664 """ Overridden to avoid duplicating fields that are unique to each email """
667 default.update(message_id=False, headers=False)
668 return super(mail_message, self).copy(cr, uid, id, default=default, context=context)
670 #------------------------------------------------------
672 #------------------------------------------------------
674 # TDE note: this code is not used currently, will be improved in a future merge, when quoted context
675 # will be added to email send for notifications. Currently only WIP.
676 MAIL_TEMPLATE = """<div>
678 ${display_message(message)}
680 % for ctx_msg in context_messages:
681 ${display_message(ctx_msg)}
684 ${display_expandable()}
686 ${display_message(header_message)}
689 <%def name="display_message(message)">
691 Subject: ${message.subject}<br />
692 Body: ${message.body}
696 <%def name="display_expandable()">
697 <div>This is an expandable.</div>
701 def message_quote_context(self, cr, uid, id, context=None, limit=3, add_original=False):
703 1. message.parent_id = False: new thread, no quote_context
704 2. get the lasts messages in the thread before message
705 3. get the message header
706 4. add an expandable between them
708 :param dict quote_context: options for quoting
709 :return string: html quote
711 add_expandable = False
713 message = self.browse(cr, uid, id, context=context)
714 if not message.parent_id:
716 context_ids = self.search(cr, uid, [
717 ('parent_id', '=', message.parent_id.id),
718 ('id', '<', message.id),
719 ], limit=limit, context=context)
721 if len(context_ids) >= limit:
722 add_expandable = True
723 context_ids = context_ids[0:-1]
725 context_ids.append(message.parent_id.id)
726 context_messages = self.browse(cr, uid, context_ids, context=context)
727 header_message = context_messages.pop()
732 result = MakoTemplate(self.MAIL_TEMPLATE).render_unicode(message=message,
733 context_messages=context_messages,
734 header_message=header_message,
735 add_expandable=add_expandable,
736 # context kw would clash with mako internals
738 format_exceptions=True)
739 result = result.strip()
742 _logger.exception("failed to render mako template for quoting message")
746 def _notify(self, cr, uid, newid, context=None):
747 """ Add the related record followers to the destination partner_ids if is not a private message.
748 Call mail_notification.notify to manage the email sending
750 message = self.read(cr, uid, newid, ['model', 'res_id', 'author_id', 'subtype_id', 'partner_ids'], context=context)
752 partners_to_notify = set([])
753 # message has no subtype_id: pure log message -> no partners, no one notified
754 if not message.get('subtype_id'):
756 # all partner_ids of the mail.message have to be notified
757 if message.get('partner_ids'):
758 partners_to_notify |= set(message.get('partner_ids'))
759 # all followers of the mail.message document have to be added as partners and notified
760 if message.get('model') and message.get('res_id'):
761 fol_obj = self.pool.get("mail.followers")
762 fol_ids = fol_obj.search(cr, uid, [
763 ('res_model', '=', message.get('model')),
764 ('res_id', '=', message.get('res_id')),
765 ('subtype_ids', 'in', message.get('subtype_id')[0])
767 fol_objs = fol_obj.read(cr, uid, fol_ids, ['partner_id'], context=context)
768 partners_to_notify |= set(fol['partner_id'][0] for fol in fol_objs)
769 # remove me from notified partners, unless the message is written on my own wall
770 if message.get('author_id') and message.get('model') == "res.partner" and message.get('res_id') == message.get('author_id')[0]:
771 partners_to_notify |= set([message.get('author_id')[0]])
772 elif message.get('author_id'):
773 partners_to_notify = partners_to_notify - set([message.get('author_id')[0]])
775 if partners_to_notify:
776 self.write(cr, SUPERUSER_ID, [newid], {'notified_partner_ids': [(4, p_id) for p_id in partners_to_notify]}, context=context)
778 self.pool.get('mail.notification')._notify(cr, uid, newid, context=context)
780 #------------------------------------------------------
782 #------------------------------------------------------
784 def check_partners_email(self, cr, uid, partner_ids, context=None):
785 """ Verify that selected partner_ids have an email_address defined.
786 Otherwise throw a warning. """
787 partner_wo_email_lst = []
788 for partner in self.pool.get('res.partner').browse(cr, uid, partner_ids, context=context):
789 if not partner.email:
790 partner_wo_email_lst.append(partner)
791 if not partner_wo_email_lst:
793 warning_msg = _('The following partners chosen as recipients for the email have no email address linked :')
794 for partner in partner_wo_email_lst:
795 warning_msg += '\n- %s' % (partner.name)
797 'title': _('Partners email addresses not found'),
798 'message': warning_msg,