[FIX] sent mail, quote template controller name
[odoo/odoo.git] / addons / email_template / email_template.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2009 Sharoon Thomas
6 #    Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
20 #
21 ##############################################################################
22
23 import base64
24 import datetime
25 import dateutil.relativedelta as relativedelta
26 import logging
27
28 import openerp
29 from openerp import SUPERUSER_ID
30 from openerp.osv import osv, fields
31 from openerp import tools
32 from openerp.tools.translate import _
33 from urllib import urlencode, quote as quote
34
35
36 _logger = logging.getLogger(__name__)
37
38 try:
39     # We use a jinja2 sandboxed environment to render mako templates.
40     # Note that the rendering does not cover all the mako syntax, in particular
41     # arbitrary Python statements are not accepted, and not all expressions are
42     # allowed: only "public" attributes (not starting with '_') of objects may
43     # be accessed.
44     # This is done on purpose: it prevents incidental or malicious execution of
45     # Python code that may break the security of the server.
46     from jinja2.sandbox import SandboxedEnvironment
47     mako_template_env = SandboxedEnvironment(
48         block_start_string="<%",
49         block_end_string="%>",
50         variable_start_string="${",
51         variable_end_string="}",
52         comment_start_string="<%doc>",
53         comment_end_string="</%doc>",
54         line_statement_prefix="%",
55         line_comment_prefix="##",
56         trim_blocks=True,               # do not output newline after blocks
57         autoescape=True,                # XML/HTML automatic escaping
58     )
59     mako_template_env.globals.update({
60         'str': str,
61         'quote': quote,
62         'urlencode': urlencode,
63         'datetime': datetime,
64
65         # dateutil.relativedelta is an old-style class and cannot be directly
66         # instanciated wihtin a jinja2 expression, so a lambda "proxy" is
67         # is needed, apparently.
68         'relativedelta': lambda *a, **kw : relativedelta.relativedelta(*a, **kw),
69     })
70 except ImportError:
71     _logger.warning("jinja2 not available, templating features will not work!")
72
73 class email_template(osv.osv):
74     "Templates for sending email"
75     _name = "email.template"
76     _description = 'Email Templates'
77     _order = 'name'
78
79     def render_template_batch(self, cr, uid, template, model, res_ids, context=None):
80         """Render the given template text, replace mako expressions ``${expr}``
81            with the result of evaluating these expressions with
82            an evaluation context containing:
83
84                 * ``user``: browse_record of the current user
85                 * ``object``: browse_record of the document record this mail is
86                               related to
87                 * ``context``: the context passed to the mail composition wizard
88
89            :param str template: the template text to render
90            :param str model: model name of the document record this mail is related to.
91            :param int res_ids: list of ids of document records those mails are related to.
92         """
93         if context is None:
94             context = {}
95         results = dict.fromkeys(res_ids, u"")
96
97         # try to load the template
98         try:
99             template = mako_template_env.from_string(tools.ustr(template))
100         except Exception:
101             _logger.exception("Failed to load template %r", template)
102             return results
103
104         # prepare template variables
105         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
106         records = self.pool[model].browse(cr, uid, res_ids, context=context) or [None]
107         variables = {
108             'user': user,
109             'ctx': context,  # context kw would clash with mako internals
110         }
111         for record in records:
112             res_id = record.id if record else None
113             variables['object'] = record
114             try:
115                 render_result = template.render(variables)
116             except Exception:
117                 _logger.exception("Failed to render template %r using values %r" % (template, variables))
118                 render_result = u""
119             if render_result == u"False":
120                 render_result = u""
121             results[res_id] = render_result
122         return results
123
124     def get_email_template_batch(self, cr, uid, template_id=False, res_ids=None, context=None):
125         if context is None:
126             context = {}
127         if res_ids is None:
128             res_ids = [None]
129         results = dict.fromkeys(res_ids, False)
130
131         if not template_id:
132             return results
133         template = self.browse(cr, uid, template_id, context)
134         langs = self.render_template_batch(cr, uid, template.lang, template.model, res_ids, context)
135         for res_id, lang in langs.iteritems():
136             if lang:
137                 # Use translated template if necessary
138                 ctx = context.copy()
139                 ctx['lang'] = lang
140                 template = self.browse(cr, uid, template.id, ctx)
141             else:
142                 template = self.browse(cr, uid, int(template_id), context)
143             results[res_id] = template
144         return results
145
146     def onchange_model_id(self, cr, uid, ids, model_id, context=None):
147         mod_name = False
148         if model_id:
149             mod_name = self.pool.get('ir.model').browse(cr, uid, model_id, context).model
150         return {'value': {'model': mod_name}}
151
152     _columns = {
153         'name': fields.char('Name'),
154         'model_id': fields.many2one('ir.model', 'Applies to', help="The kind of document with with this template can be used"),
155         'model': fields.related('model_id', 'model', type='char', string='Related Document Model',
156                                 size=128, select=True, store=True, readonly=True),
157         'lang': fields.char('Language',
158                             help="Optional translation language (ISO code) to select when sending out an email. "
159                                  "If not set, the english version will be used. "
160                                  "This should usually be a placeholder expression "
161                                  "that provides the appropriate language code, e.g. "
162                                  "${object.partner_id.lang.code}.",
163                             placeholder="${object.partner_id.lang.code}"),
164         'user_signature': fields.boolean('Add Signature',
165                                          help="If checked, the user's signature will be appended to the text version "
166                                               "of the message"),
167         'subject': fields.char('Subject', translate=True, help="Subject (placeholders may be used here)",),
168         'email_from': fields.char('From',
169             help="Sender address (placeholders may be used here). If not set, the default "
170                     "value will be the author's email alias if configured, or email address."),
171         'email_to': fields.char('To (Emails)', help="Comma-separated recipient addresses (placeholders may be used here)"),
172         'partner_to': fields.char('To (Partners)',
173             help="Comma-separated ids of recipient partners (placeholders may be used here)",
174             oldname='email_recipients'),
175         'email_cc': fields.char('Cc', help="Carbon copy recipients (placeholders may be used here)"),
176         'reply_to': fields.char('Reply-To', help="Preferred response address (placeholders may be used here)"),
177         'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing Mail Server', readonly=False,
178                                           help="Optional preferred server for outgoing mails. If not set, the highest "
179                                                "priority one will be used."),
180         'body_html': fields.html('Body', translate=True, help="Rich-text/HTML version of the message (placeholders may be used here)"),
181         'report_name': fields.char('Report Filename', translate=True,
182                                    help="Name to use for the generated report file (may contain placeholders)\n"
183                                         "The extension can be omitted and will then come from the report type."),
184         'report_template': fields.many2one('ir.actions.report.xml', 'Optional report to print and attach'),
185         'ref_ir_act_window': fields.many2one('ir.actions.act_window', 'Sidebar action', readonly=True,
186                                             help="Sidebar action to make this template available on records "
187                                                  "of the related document model"),
188         'ref_ir_value': fields.many2one('ir.values', 'Sidebar Button', readonly=True,
189                                        help="Sidebar button to open the sidebar action"),
190         'attachment_ids': fields.many2many('ir.attachment', 'email_template_attachment_rel', 'email_template_id',
191                                            'attachment_id', 'Attachments',
192                                            help="You may attach files to this template, to be added to all "
193                                                 "emails created from this template"),
194         'auto_delete': fields.boolean('Auto Delete', help="Permanently delete this email after sending it, to save space"),
195
196         # Fake fields used to implement the placeholder assistant
197         'model_object_field': fields.many2one('ir.model.fields', string="Field",
198                                               help="Select target field from the related document model.\n"
199                                                    "If it is a relationship field you will be able to select "
200                                                    "a target field at the destination of the relationship."),
201         'sub_object': fields.many2one('ir.model', 'Sub-model', readonly=True,
202                                       help="When a relationship field is selected as first field, "
203                                            "this field shows the document model the relationship goes to."),
204         'sub_model_object_field': fields.many2one('ir.model.fields', 'Sub-field',
205                                                   help="When a relationship field is selected as first field, "
206                                                        "this field lets you select the target field within the "
207                                                        "destination document model (sub-model)."),
208         'null_value': fields.char('Default Value', help="Optional value to use if the target field is empty"),
209         'copyvalue': fields.char('Placeholder Expression', help="Final placeholder expression, to be copy-pasted in the desired template field."),
210     }
211
212     _defaults = {
213         'auto_delete': True,
214     }
215
216     def create_action(self, cr, uid, ids, context=None):
217         action_obj = self.pool.get('ir.actions.act_window')
218         data_obj = self.pool.get('ir.model.data')
219         for template in self.browse(cr, uid, ids, context=context):
220             src_obj = template.model_id.model
221             model_data_id = data_obj._get_id(cr, uid, 'mail', 'email_compose_message_wizard_form')
222             res_id = data_obj.browse(cr, uid, model_data_id, context=context).res_id
223             button_name = _('Send Mail (%s)') % template.name
224             act_id = action_obj.create(cr, SUPERUSER_ID, {
225                  'name': button_name,
226                  'type': 'ir.actions.act_window',
227                  'res_model': 'mail.compose.message',
228                  'src_model': src_obj,
229                  'view_type': 'form',
230                  'context': "{'default_composition_mode': 'mass_mail', 'default_template_id' : %d, 'default_use_template': True}" % (template.id),
231                  'view_mode':'form,tree',
232                  'view_id': res_id,
233                  'target': 'new',
234                  'auto_refresh':1
235             }, context)
236             ir_values_id = self.pool.get('ir.values').create(cr, SUPERUSER_ID, {
237                  'name': button_name,
238                  'model': src_obj,
239                  'key2': 'client_action_multi',
240                  'value': "ir.actions.act_window,%s" % act_id,
241                  'object': True,
242              }, context)
243
244             template.write({
245                 'ref_ir_act_window': act_id,
246                 'ref_ir_value': ir_values_id,
247             })
248
249         return True
250
251     def unlink_action(self, cr, uid, ids, context=None):
252         for template in self.browse(cr, uid, ids, context=context):
253             try:
254                 if template.ref_ir_act_window:
255                     self.pool.get('ir.actions.act_window').unlink(cr, SUPERUSER_ID, template.ref_ir_act_window.id, context)
256                 if template.ref_ir_value:
257                     ir_values_obj = self.pool.get('ir.values')
258                     ir_values_obj.unlink(cr, SUPERUSER_ID, template.ref_ir_value.id, context)
259             except Exception:
260                 raise osv.except_osv(_("Warning"), _("Deletion of the action record failed."))
261         return True
262
263     def unlink(self, cr, uid, ids, context=None):
264         self.unlink_action(cr, uid, ids, context=context)
265         return super(email_template, self).unlink(cr, uid, ids, context=context)
266
267     def copy(self, cr, uid, id, default=None, context=None):
268         template = self.browse(cr, uid, id, context=context)
269         if default is None:
270             default = {}
271         default = default.copy()
272         default.update(
273             name=_("%s (copy)") % (template.name),
274             ref_ir_act_window=False,
275             ref_ir_value=False)
276         return super(email_template, self).copy(cr, uid, id, default, context)
277
278     def build_expression(self, field_name, sub_field_name, null_value):
279         """Returns a placeholder expression for use in a template field,
280            based on the values provided in the placeholder assistant.
281
282           :param field_name: main field name
283           :param sub_field_name: sub field name (M2O)
284           :param null_value: default value if the target value is empty
285           :return: final placeholder expression
286         """
287         expression = ''
288         if field_name:
289             expression = "${object." + field_name
290             if sub_field_name:
291                 expression += "." + sub_field_name
292             if null_value:
293                 expression += " or '''%s'''" % null_value
294             expression += "}"
295         return expression
296
297     def onchange_sub_model_object_value_field(self, cr, uid, ids, model_object_field, sub_model_object_field=False, null_value=None, context=None):
298         result = {
299             'sub_object': False,
300             'copyvalue': False,
301             'sub_model_object_field': False,
302             'null_value': False
303             }
304         if model_object_field:
305             fields_obj = self.pool.get('ir.model.fields')
306             field_value = fields_obj.browse(cr, uid, model_object_field, context)
307             if field_value.ttype in ['many2one', 'one2many', 'many2many']:
308                 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_value.relation)], context=context)
309                 sub_field_value = False
310                 if sub_model_object_field:
311                     sub_field_value = fields_obj.browse(cr, uid, sub_model_object_field, context)
312                 if res_ids:
313                     result.update({
314                         'sub_object': res_ids[0],
315                         'copyvalue': self.build_expression(field_value.name, sub_field_value and sub_field_value.name or False, null_value or False),
316                         'sub_model_object_field': sub_model_object_field or False,
317                         'null_value': null_value or False
318                         })
319             else:
320                 result.update({
321                         'copyvalue': self.build_expression(field_value.name, False, null_value or False),
322                         'null_value': null_value or False
323                         })
324         return {'value': result}
325
326     def generate_email_batch(self, cr, uid, template_id, res_ids, context=None, fields=None):
327         """Generates an email from the template for given the given model based on
328         records given by res_ids.
329
330         :param template_id: id of the template to render.
331         :param res_id: id of the record to use for rendering the template (model
332                        is taken from template definition)
333         :returns: a dict containing all relevant fields for creating a new
334                   mail.mail entry, with one extra key ``attachments``, in the
335                   format expected by :py:meth:`mail_thread.message_post`.
336         """
337         if context is None:
338             context = {}
339         if fields is None:
340             fields = ['subject', 'body_html', 'email_from', 'email_to', 'partner_to', 'email_cc', 'reply_to']
341
342         report_xml_pool = self.pool.get('ir.actions.report.xml')
343         res_ids_to_templates = self.get_email_template_batch(cr, uid, template_id, res_ids, context)
344
345         # templates: res_id -> template; template -> res_ids
346         templates_to_res_ids = {}
347         for res_id, template in res_ids_to_templates.iteritems():
348             templates_to_res_ids.setdefault(template, []).append(res_id)
349
350         results = dict()
351         for template, template_res_ids in templates_to_res_ids.iteritems():
352             # generate fields value for all res_ids linked to the current template
353             for field in ['subject', 'body_html', 'email_from', 'email_to', 'partner_to', 'email_cc', 'reply_to']:
354                 generated_field_values = self.render_template_batch(cr, uid, getattr(template, field), template.model, template_res_ids, context=context)
355                 for res_id, field_value in generated_field_values.iteritems():
356                     results.setdefault(res_id, dict())[field] = field_value
357             # update values for all res_ids
358             for res_id in template_res_ids:
359                 values = results[res_id]
360                 if template.user_signature:
361                     signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
362                     values['body_html'] = tools.append_content_to_html(values['body_html'], signature)
363                 if values['body_html']:
364                     values['body'] = tools.html_sanitize(values['body_html'])
365                 values.update(
366                     mail_server_id=template.mail_server_id.id or False,
367                     auto_delete=template.auto_delete,
368                     model=template.model,
369                     res_id=res_id or False,
370                     attachment_ids=[attach.id for attach in template.attachment_ids],
371                 )
372
373             # Add report in attachments: generate once for all template_res_ids
374             if template.report_template:
375                 for res_id in template_res_ids:
376                     attachments = []
377                     report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context)
378                     report_service = report_xml_pool.browse(cr, uid, template.report_template.id, context).report_name
379                     # Ensure report is rendered using template's language
380                     ctx = context.copy()
381                     if template.lang:
382                         ctx['lang'] = self.render_template_batch(cr, uid, template.lang, template.model, [res_id], context)[res_id]  # take 0 ?
383                     result, format = openerp.report.render_report(cr, uid, [res_id], report_service, {'model': template.model}, ctx)
384                     result = base64.b64encode(result)
385                     if not report_name:
386                         report_name = 'report.' + report_service
387                     ext = "." + format
388                     if not report_name.endswith(ext):
389                         report_name += ext
390                     attachments.append((report_name, result))
391                     results[res_id]['attachments'] = attachments
392
393         return results
394
395     def send_mail(self, cr, uid, template_id, res_id, force_send=False, raise_exception=False, context=None):
396         """Generates a new mail message for the given template and record,
397            and schedules it for delivery through the ``mail`` module's scheduler.
398
399            :param int template_id: id of the template to render
400            :param int res_id: id of the record to render the template with
401                               (model is taken from the template)
402            :param bool force_send: if True, the generated mail.message is
403                 immediately sent after being created, as if the scheduler
404                 was executed for this message only.
405            :returns: id of the mail.message that was created
406         """
407         if context is None:
408             context = {}
409         mail_mail = self.pool.get('mail.mail')
410         ir_attachment = self.pool.get('ir.attachment')
411
412         # create a mail_mail based on values, without attachments
413         values = self.generate_email(cr, uid, template_id, res_id, context=context)
414         assert values.get('email_from'), 'email_from is missing or empty after template rendering, send_mail() cannot proceed'
415
416         # process partner_to field that is a comma separated list of partner_ids -> recipient_ids
417         # NOTE: only usable if force_send is True, because otherwise the value is
418         # not stored on the mail_mail, and therefore lost -> fixed in v8
419         values['recipient_ids'] = []
420         partner_to = values.pop('partner_to', '')
421         if partner_to:
422             # placeholders could generate '', 3, 2 due to some empty field values
423             tpl_partner_ids = [pid for pid in partner_to.split(',') if pid]
424             values['recipient_ids'] += [(4, pid) for pid in self.pool['res.partner'].exists(cr, SUPERUSER_ID, tpl_partner_ids, context=context)]
425
426         attachment_ids = values.pop('attachment_ids', [])
427         attachments = values.pop('attachments', [])
428         msg_id = mail_mail.create(cr, uid, values, context=context)
429         mail = mail_mail.browse(cr, uid, msg_id, context=context)
430
431         # manage attachments
432         for attachment in attachments:
433             attachment_data = {
434                 'name': attachment[0],
435                 'datas_fname': attachment[0],
436                 'datas': attachment[1],
437                 'res_model': 'mail.message',
438                 'res_id': mail.mail_message_id.id,
439             }
440             context.pop('default_type', None)
441             attachment_ids.append(ir_attachment.create(cr, uid, attachment_data, context=context))
442         if attachment_ids:
443             values['attachment_ids'] = [(6, 0, attachment_ids)]
444             mail_mail.write(cr, uid, msg_id, {'attachment_ids': [(6, 0, attachment_ids)]}, context=context)
445
446         if force_send:
447             mail_mail.send(cr, uid, [msg_id], raise_exception=raise_exception, context=context)
448         return msg_id
449
450     # Compatibility method
451     def render_template(self, cr, uid, template, model, res_id, context=None):
452         return self.render_template_batch(cr, uid, template, model, [res_id], context)[res_id]
453
454     def get_email_template(self, cr, uid, template_id=False, record_id=None, context=None):
455         return self.get_email_template_batch(cr, uid, template_id, [record_id], context)[record_id]
456
457     def generate_email(self, cr, uid, template_id, res_id, context=None):
458         return self.generate_email_batch(cr, uid, template_id, [res_id], context)[res_id]
459
460 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: