[MERGE]: Merged with addons
[odoo/odoo.git] / addons / mail / wizard / mail_compose_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 General Public License as published by
9 #    the Free Software Foundation, either version 3 of the License, or
10 #    (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 General Public License for more details.
16 #
17 #    You should have received a copy of the GNU General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
19 #
20 ##############################################################################
21
22 import re
23 from openerp import tools
24 from openerp import SUPERUSER_ID
25 from openerp.osv import osv
26 from openerp.osv import fields
27 from openerp.tools.safe_eval import safe_eval as eval
28 from openerp.tools.translate import _
29
30 # main mako-like expression pattern
31 EXPRESSION_PATTERN = re.compile('(\$\{.+?\})')
32
33
34 class mail_compose_message(osv.TransientModel):
35     """ Generic message composition wizard. You may inherit from this wizard
36         at model and view levels to provide specific features.
37
38         The behavior of the wizard depends on the composition_mode field:
39         - 'reply': reply to a previous message. The wizard is pre-populated
40             via ``get_message_data``.
41         - 'comment': new post on a record. The wizard is pre-populated via
42             ``get_record_data``
43         - 'mass_mail': wizard in mass mailing mode where the mail details can
44             contain template placeholders that will be merged with actual data
45             before being sent to each recipient.
46     """
47     _name = 'mail.compose.message'
48     _inherit = 'mail.message'
49     _description = 'Email composition wizard'
50     _log_access = True
51
52     def default_get(self, cr, uid, fields, context=None):
53         """ Handle composition mode. Some details about context keys:
54             - comment: default mode, model and ID of a record the user comments
55                 - default_model or active_model
56                 - default_res_id or active_id
57             - reply: active_id of a message the user replies to
58                 - default_parent_id or message_id or active_id: ID of the
59                     mail.message we reply to
60                 - message.res_model or default_model
61                 - message.res_id or default_res_id
62             - mass_mail: model and IDs of records the user mass-mails
63                 - active_ids: record IDs
64                 - default_model or active_model
65         """
66         if context is None:
67             context = {}
68         result = super(mail_compose_message, self).default_get(cr, uid, fields, context=context)
69         # get some important values from context
70         composition_mode = context.get('default_composition_mode', context.get('mail.compose.message.mode'))
71         model = context.get('default_model', context.get('active_model'))
72         res_id = context.get('default_res_id', context.get('active_id'))
73         message_id = context.get('default_parent_id', context.get('message_id', context.get('active_id')))
74         active_ids = context.get('active_ids')
75         if 'active_domain' in context:  # not context.get() because we want to keep global [] domains
76             result['use_active_domain'] = True
77             result['active_domain'] = '%s' % context.get('active_domain')
78         else:
79             result['active_domain'] = ''
80         # get default values according to the composition mode
81         if composition_mode == 'reply':
82             vals = self.get_message_data(cr, uid, message_id, context=context)
83         elif composition_mode == 'comment' and model and res_id:
84             vals = self.get_record_data(cr, uid, model, res_id, context=context)
85         elif composition_mode == 'mass_mail' and model and active_ids:
86             vals = {'model': model, 'res_id': res_id}
87         else:
88             vals = {'model': model, 'res_id': res_id}
89         if composition_mode:
90             vals['composition_mode'] = composition_mode
91
92         for field in vals:
93             if field in fields:
94                 result[field] = vals[field]
95
96         # TDE HACK: as mailboxes used default_model='res.users' and default_res_id=uid
97         # (because of lack of an accessible pid), creating a message on its own
98         # profile may crash (res_users does not allow writing on it)
99         # Posting on its own profile works (res_users redirect to res_partner)
100         # but when creating the mail.message to create the mail.compose.message
101         # access rights issues may rise
102         # We therefore directly change the model and res_id
103         if result.get('model') == 'res.users' and result.get('res_id') == uid:
104             result['model'] = 'res.partner'
105             result['res_id'] = self.pool.get('res.users').browse(cr, uid, uid).partner_id.id
106         return result
107
108     def _get_composition_mode_selection(self, cr, uid, context=None):
109         return [('comment', 'Comment a document'), ('reply', 'Reply to a message'), ('mass_mail', 'Mass mailing')]
110
111     _columns = {
112         'composition_mode': fields.selection(
113             lambda s, *a, **k: s._get_composition_mode_selection(*a, **k),
114             string='Composition mode'),
115         'partner_ids': fields.many2many('res.partner',
116             'mail_compose_message_res_partner_rel',
117             'wizard_id', 'partner_id', 'Additional contacts'),
118         'use_active_domain': fields.boolean('Use active domain'),
119         'active_domain': fields.char('Active domain', readonly=True),
120         'post': fields.boolean('Post a copy in the document',
121             help='Post a copy of the message on the document communication history.'),
122         'notify': fields.boolean('Notify followers',
123             help='Notify followers of the document'),
124         'same_thread': fields.boolean('Replies in the document',
125             help='Replies to the messages will go into the selected document.'),
126         'attachment_ids': fields.many2many('ir.attachment',
127             'mail_compose_message_ir_attachments_rel',
128             'wizard_id', 'attachment_id', 'Attachments'),
129         'filter_id': fields.many2one('ir.filters', 'Filters'),
130     }
131
132     _defaults = {
133         'composition_mode': 'comment',
134         'body': lambda self, cr, uid, ctx={}: '',
135         'subject': lambda self, cr, uid, ctx={}: False,
136         'partner_ids': lambda self, cr, uid, ctx={}: [],
137         'post': lambda self, cr, uid, ctx={}: True,
138         'same_thread': lambda self, cr, uid, ctx={}: True,
139     }
140
141     def check_access_rule(self, cr, uid, ids, operation, context=None):
142         """ Access rules of mail.compose.message:
143             - create: if
144                 - model, no res_id, I create a message in mass mail mode
145             - then: fall back on mail.message acces rules
146         """
147         if isinstance(ids, (int, long)):
148             ids = [ids]
149
150         # Author condition (CREATE (mass_mail))
151         if operation == 'create' and uid != SUPERUSER_ID:
152             # read mail_compose_message.ids to have their values
153             message_values = {}
154             cr.execute('SELECT DISTINCT id, model, res_id FROM "%s" WHERE id = ANY (%%s) AND res_id = 0' % self._table, (ids,))
155             for id, rmod, rid in cr.fetchall():
156                 message_values[id] = {'model': rmod, 'res_id': rid}
157             # remove from the set to check the ids that mail_compose_message accepts
158             author_ids = [mid for mid, message in message_values.iteritems()
159                 if message.get('model') and not message.get('res_id')]
160             ids = list(set(ids) - set(author_ids))
161
162         return super(mail_compose_message, self).check_access_rule(cr, uid, ids, operation, context=context)
163
164     def _notify(self, cr, uid, newid, context=None, force_send=False, user_signature=True):
165         """ Override specific notify method of mail.message, because we do
166             not want that feature in the wizard. """
167         return
168
169     def get_record_data(self, cr, uid, model, res_id, context=None):
170         """ Returns a defaults-like dict with initial values for the composition
171             wizard when sending an email related to the document record
172             identified by ``model`` and ``res_id``.
173
174             :param str model: model name of the document record this mail is
175                 related to.
176             :param int res_id: id of the document record this mail is related to
177         """
178         doc_name_get = self.pool[model].name_get(cr, uid, [res_id], context=context)
179         record_name = False
180         if doc_name_get:
181             record_name = doc_name_get[0][1]
182         values = {
183             'model': model,
184             'res_id': res_id,
185             'record_name': record_name,
186         }
187         if record_name:
188             values['subject'] = 'Re: %s' % record_name
189         return values
190
191     def get_message_data(self, cr, uid, message_id, context=None):
192         """ Returns a defaults-like dict with initial values for the composition
193             wizard when replying to the given message (e.g. including the quote
194             of the initial message, and the correct recipients).
195
196             :param int message_id: id of the mail.message to which the user
197                 is replying.
198         """
199         if not message_id:
200             return {}
201         if context is None:
202             context = {}
203         message_data = self.pool.get('mail.message').browse(cr, uid, message_id, context=context)
204
205         # create subject
206         re_prefix = _('Re:')
207         reply_subject = tools.ustr(message_data.subject or message_data.record_name or '')
208         if not (reply_subject.startswith('Re:') or reply_subject.startswith(re_prefix)) and message_data.subject:
209             reply_subject = "%s %s" % (re_prefix, reply_subject)
210         # get partner_ids from original message
211         partner_ids = [partner.id for partner in message_data.partner_ids] if message_data.partner_ids else []
212         partner_ids += context.get('default_partner_ids', [])
213         if context.get('is_private',False) and message_data.author_id : #check message is private then add author also in partner list.
214             partner_ids += [message_data.author_id.id]
215         # update the result
216         result = {
217             'record_name': message_data.record_name,
218             'model': message_data.model,
219             'res_id': message_data.res_id,
220             'parent_id': message_data.id,
221             'subject': reply_subject,
222             'partner_ids': partner_ids,
223         }
224         return result
225
226     #------------------------------------------------------
227     # Wizard validation and send
228     #------------------------------------------------------
229
230     def send_mail(self, cr, uid, ids, context=None):
231         """ Process the wizard content and proceed with sending the related
232             email(s), rendering any template patterns on the fly if needed. """
233         if context is None:
234             context = {}
235         ir_attachment_obj = self.pool.get('ir.attachment')
236         active_ids = context.get('active_ids')
237         is_log = context.get('mail_compose_log', False)
238
239         for wizard in self.browse(cr, uid, ids, context=context):
240             mass_mail_mode = wizard.composition_mode == 'mass_mail'
241             active_model_pool = self.pool[wizard.model if wizard.model else 'mail.thread']
242             if not hasattr(active_model_pool, 'message_post'):
243                 context['thread_model'] = wizard.model
244                 active_model_pool = self.pool['mail.thread']
245
246             # wizard works in batch mode: [res_id] or active_ids or active_domain
247             if mass_mail_mode and wizard.use_active_domain and wizard.model:
248                 res_ids = self.pool[wizard.model].search(cr, uid, eval(wizard.active_domain), context=context)
249             elif mass_mail_mode and wizard.model and active_ids:
250                 res_ids = active_ids
251             else:
252                 res_ids = [wizard.res_id]
253
254             for res_id in res_ids:
255                 # mail.message values, according to the wizard options
256                 post_values = {
257                     'subject': wizard.subject,
258                     'body': wizard.body,
259                     'parent_id': wizard.parent_id and wizard.parent_id.id,
260                     'partner_ids': [partner.id for partner in wizard.partner_ids],
261                     'attachment_ids': [attach.id for attach in wizard.attachment_ids],
262                 }
263                 # mass mailing: render and override default values
264                 if mass_mail_mode and wizard.model:
265                     email_dict = self.render_message(cr, uid, wizard, res_id, context=context)
266                     post_values['partner_ids'] += email_dict.pop('partner_ids', [])
267                     post_values['attachments'] = email_dict.pop('attachments', [])
268                     attachment_ids = []
269                     for attach_id in post_values.pop('attachment_ids'):
270                         new_attach_id = ir_attachment_obj.copy(cr, uid, attach_id, {'res_model': self._name, 'res_id': wizard.id}, context=context)
271                         attachment_ids.append(new_attach_id)
272                     post_values['attachment_ids'] = attachment_ids
273                     # email_from: mass mailing only can specify another email_from
274                     if email_dict.get('email_from'):
275                         post_values['email_from'] = email_dict.pop('email_from')
276                     # replies redirection: mass mailing only
277                     if not wizard.same_thread:
278                         post_values['reply_to'] = email_dict.pop('reply_to')
279                     else:
280                         email_dict.pop('reply_to')
281                     post_values.update(email_dict)
282                 # clean the context (hint: mass mailing sets some default values that
283                 # could be wrongly interpreted by mail_mail)
284                 context.pop('default_email_to', None)
285                 context.pop('default_partner_ids', None)
286                 # post the message
287                 if mass_mail_mode and not wizard.post:
288                     post_values['body_html'] = post_values.get('body', '')
289                     post_values['recipient_ids'] = [(4, id) for id in post_values.pop('partner_ids', [])]
290                     self.pool.get('mail.mail').create(cr, uid, post_values, context=context)
291                 else:
292                     subtype = 'mail.mt_comment'
293                     if is_log:  # log a note: subtype is False
294                         subtype = False
295                     elif mass_mail_mode:  # mass mail: is a log pushed to recipients unless specified, author not added
296                         if not wizard.notify:
297                             subtype = False
298                         context = dict(context,
299                                     mail_notify_force_send=False,  # do not send emails directly but use the queue instead
300                                     mail_create_nosubscribe=True)  # add context key to avoid subscribing the author
301                     active_model_pool.message_post(cr, uid, [res_id], type='comment', subtype=subtype, context=context, **post_values)
302
303         return {'type': 'ir.actions.act_window_close'}
304
305     def render_message(self, cr, uid, wizard, res_id, context=None):
306         """ Generate an email from the template for given (wizard.model, res_id)
307             pair. This method is meant to be inherited by email_template that
308             will produce a more complete dictionary. """
309         return {
310             'subject': self.render_template(cr, uid, wizard.subject, wizard.model, res_id, context),
311             'body': self.render_template(cr, uid, wizard.body, wizard.model, res_id, context),
312             'email_from': self.render_template(cr, uid, wizard.email_from, wizard.model, res_id, context),
313             'reply_to': self.render_template(cr, uid, wizard.reply_to, wizard.model, res_id, context),
314         }
315
316     def render_template(self, cr, uid, template, model, res_id, context=None):
317         """ Render the given template text, replace mako-like expressions ``${expr}``
318             with the result of evaluating these expressions with an evaluation context
319             containing:
320
321                 * ``user``: browse_record of the current user
322                 * ``object``: browse_record of the document record this mail is
323                               related to
324                 * ``context``: the context passed to the mail composition wizard
325
326             :param str template: the template text to render
327             :param str model: model name of the document record this mail is related to.
328             :param int res_id: id of the document record this mail is related to.
329         """
330         if context is None:
331             context = {}
332
333         def merge(match):
334             exp = str(match.group()[2:-1]).strip()
335             result = eval(exp, {
336                 'user': self.pool.get('res.users').browse(cr, uid, uid, context=context),
337                 'object': self.pool[model].browse(cr, uid, res_id, context=context),
338                 'context': dict(context),  # copy context to prevent side-effects of eval
339                 })
340             return result and tools.ustr(result) or ''
341         return template and EXPRESSION_PATTERN.sub(merge, template)