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