Merge pull request #232 from odoo-dev/saas-4-mass_mailing-fixes-tde
[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 import lxml
28 import urlparse
29
30 import openerp
31 from openerp import SUPERUSER_ID
32 from openerp.osv import osv, fields
33 from openerp import tools
34 from openerp.tools.translate import _
35 from urllib import urlencode, quote as quote
36
37
38 _logger = logging.getLogger(__name__)
39
40 try:
41     # We use a jinja2 sandboxed environment to render mako templates.
42     # Note that the rendering does not cover all the mako syntax, in particular
43     # arbitrary Python statements are not accepted, and not all expressions are
44     # allowed: only "public" attributes (not starting with '_') of objects may
45     # be accessed.
46     # This is done on purpose: it prevents incidental or malicious execution of
47     # Python code that may break the security of the server.
48     from jinja2.sandbox import SandboxedEnvironment
49     mako_template_env = SandboxedEnvironment(
50         block_start_string="<%",
51         block_end_string="%>",
52         variable_start_string="${",
53         variable_end_string="}",
54         comment_start_string="<%doc>",
55         comment_end_string="</%doc>",
56         line_statement_prefix="%",
57         line_comment_prefix="##",
58         trim_blocks=True,               # do not output newline after blocks
59         autoescape=True,                # XML/HTML automatic escaping
60     )
61     mako_template_env.globals.update({
62         'str': str,
63         'quote': quote,
64         'urlencode': urlencode,
65         'datetime': datetime,
66         'len': len,
67         'abs': abs,
68         'min': min,
69         'max': max,
70         'sum': sum,
71         'filter': filter,
72         'reduce': reduce,
73         'map': map,
74         'round': round,
75
76         # dateutil.relativedelta is an old-style class and cannot be directly
77         # instanciated wihtin a jinja2 expression, so a lambda "proxy" is
78         # is needed, apparently.
79         'relativedelta': lambda *a, **kw : relativedelta.relativedelta(*a, **kw),
80     })
81 except ImportError:
82     _logger.warning("jinja2 not available, templating features will not work!")
83
84
85 class email_template(osv.osv):
86     "Templates for sending email"
87     _name = "email.template"
88     _description = 'Email Templates'
89     _order = 'name'
90
91     def default_get(self, cr, uid, fields, context=None):
92         res = super(email_template, self).default_get(cr, uid, fields, context)
93         if res.get('model'):
94             res['model_id'] = self.pool['ir.model'].search(cr, uid, [('model', '=', res.pop('model'))], context=context)[0]
95         return res
96
97     def _replace_local_links(self, cr, uid, html, context=None):
98         """ Post-processing of html content to replace local links to absolute
99         links, using web.base.url as base url. """
100         if not html:
101             return html
102
103         # form a tree
104         root = lxml.html.fromstring(html)
105         if not len(root) and root.text is None and root.tail is None:
106             html = '<div>%s</div>' % html
107             root = lxml.html.fromstring(html)
108
109         base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
110         (base_scheme, base_netloc, bpath, bparams, bquery, bfragment) = urlparse.urlparse(base_url)
111
112         def _process_link(url):
113             new_url = url
114             (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
115             if not scheme and not netloc:
116                 new_url = urlparse.urlunparse((base_scheme, base_netloc, path, params, query, fragment))
117             return new_url
118
119         # check all nodes, replace :
120         # - img src -> check URL
121         # - a href -> check URL
122         for node in root.iter():
123             if node.tag == 'a':
124                 node.set('href', _process_link(node.get('href')))
125             elif node.tag == 'img' and not node.get('src', 'data').startswith('data'):
126                 node.set('src', _process_link(node.get('src')))
127
128         html = lxml.html.tostring(root, pretty_print=False, method='html')
129         # this is ugly, but lxml/etree tostring want to put everything in a 'div' that breaks the editor -> remove that
130         if html.startswith('<div>') and html.endswith('</div>'):
131             html = html[5:-6]
132         return html
133
134     def render_post_process(self, cr, uid, html, context=None):
135         html = self._replace_local_links(cr, uid, html, context=context)
136         return html
137
138     def render_template_batch(self, cr, uid, template, model, res_ids, context=None, post_process=False):
139         """Render the given template text, replace mako expressions ``${expr}``
140            with the result of evaluating these expressions with
141            an evaluation context containing:
142
143                 * ``user``: browse_record of the current user
144                 * ``object``: browse_record of the document record this mail is
145                               related to
146                 * ``context``: the context passed to the mail composition wizard
147
148            :param str template: the template text to render
149            :param str model: model name of the document record this mail is related to.
150            :param int res_ids: list of ids of document records those mails are related to.
151         """
152         if context is None:
153             context = {}
154         results = dict.fromkeys(res_ids, u"")
155
156         # try to load the template
157         try:
158             template = mako_template_env.from_string(tools.ustr(template))
159         except Exception:
160             _logger.exception("Failed to load template %r", template)
161             return results
162
163         # prepare template variables
164         user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
165         records = self.pool[model].browse(cr, uid, res_ids, context=context) or [None]
166         variables = {
167             'user': user,
168             'ctx': context,  # context kw would clash with mako internals
169         }
170         for record in records:
171             res_id = record.id if record else None
172             variables['object'] = record
173             try:
174                 render_result = template.render(variables)
175             except Exception:
176                 _logger.exception("Failed to render template %r using values %r" % (template, variables))
177                 render_result = u""
178             if render_result == u"False":
179                 render_result = u""
180             results[res_id] = render_result
181
182         if post_process:
183             for res_id, result in results.iteritems():
184                 results[res_id] = self.render_post_process(cr, uid, result, context=context)
185         return results
186
187     def get_email_template_batch(self, cr, uid, template_id=False, res_ids=None, context=None):
188         if context is None:
189             context = {}
190         if res_ids is None:
191             res_ids = [None]
192         results = dict.fromkeys(res_ids, False)
193
194         if not template_id:
195             return results
196         template = self.browse(cr, uid, template_id, context)
197         langs = self.render_template_batch(cr, uid, template.lang, template.model, res_ids, context)
198         for res_id, lang in langs.iteritems():
199             if lang:
200                 # Use translated template if necessary
201                 ctx = context.copy()
202                 ctx['lang'] = lang
203                 template = self.browse(cr, uid, template.id, ctx)
204             else:
205                 template = self.browse(cr, uid, int(template_id), context)
206             results[res_id] = template
207         return results
208
209     def onchange_model_id(self, cr, uid, ids, model_id, context=None):
210         mod_name = False
211         if model_id:
212             mod_name = self.pool.get('ir.model').browse(cr, uid, model_id, context).model
213         return {'value': {'model': mod_name}}
214
215     _columns = {
216         'name': fields.char('Name'),
217         'model_id': fields.many2one('ir.model', 'Applies to', help="The kind of document with with this template can be used"),
218         'model': fields.related('model_id', 'model', type='char', string='Related Document Model',
219                                 size=128, select=True, store=True, readonly=True),
220         'lang': fields.char('Language',
221                             help="Optional translation language (ISO code) to select when sending out an email. "
222                                  "If not set, the english version will be used. "
223                                  "This should usually be a placeholder expression "
224                                  "that provides the appropriate language code, e.g. "
225                                  "${object.partner_id.lang.code}.",
226                             placeholder="${object.partner_id.lang.code}"),
227         'user_signature': fields.boolean('Add Signature',
228                                          help="If checked, the user's signature will be appended to the text version "
229                                               "of the message"),
230         'subject': fields.char('Subject', translate=True, help="Subject (placeholders may be used here)",),
231         'email_from': fields.char('From',
232             help="Sender address (placeholders may be used here). If not set, the default "
233                     "value will be the author's email alias if configured, or email address."),
234         'use_default_to': fields.boolean(
235             'Default recipients',
236             help="Default recipients of the record:\n"
237                  "- partner (using id on a partner or the partner_id field) OR\n"
238                  "- email (using email_from or email field)"),
239         'email_to': fields.char('To (Emails)', help="Comma-separated recipient addresses (placeholders may be used here)"),
240         'partner_to': fields.char('To (Partners)',
241             help="Comma-separated ids of recipient partners (placeholders may be used here)",
242             oldname='email_recipients'),
243         'email_cc': fields.char('Cc', help="Carbon copy recipients (placeholders may be used here)"),
244         'reply_to': fields.char('Reply-To', help="Preferred response address (placeholders may be used here)"),
245         'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing Mail Server', readonly=False,
246                                           help="Optional preferred server for outgoing mails. If not set, the highest "
247                                                "priority one will be used."),
248         'body_html': fields.html('Body', translate=True, sanitize=False, help="Rich-text/HTML version of the message (placeholders may be used here)"),
249         'report_name': fields.char('Report Filename', translate=True,
250                                    help="Name to use for the generated report file (may contain placeholders)\n"
251                                         "The extension can be omitted and will then come from the report type."),
252         'report_template': fields.many2one('ir.actions.report.xml', 'Optional report to print and attach'),
253         'ref_ir_act_window': fields.many2one('ir.actions.act_window', 'Sidebar action', readonly=True,
254                                             help="Sidebar action to make this template available on records "
255                                                  "of the related document model"),
256         'ref_ir_value': fields.many2one('ir.values', 'Sidebar Button', readonly=True,
257                                        help="Sidebar button to open the sidebar action"),
258         'attachment_ids': fields.many2many('ir.attachment', 'email_template_attachment_rel', 'email_template_id',
259                                            'attachment_id', 'Attachments',
260                                            help="You may attach files to this template, to be added to all "
261                                                 "emails created from this template"),
262         'auto_delete': fields.boolean('Auto Delete', help="Permanently delete this email after sending it, to save space"),
263
264         # Fake fields used to implement the placeholder assistant
265         'model_object_field': fields.many2one('ir.model.fields', string="Field",
266                                               help="Select target field from the related document model.\n"
267                                                    "If it is a relationship field you will be able to select "
268                                                    "a target field at the destination of the relationship."),
269         'sub_object': fields.many2one('ir.model', 'Sub-model', readonly=True,
270                                       help="When a relationship field is selected as first field, "
271                                            "this field shows the document model the relationship goes to."),
272         'sub_model_object_field': fields.many2one('ir.model.fields', 'Sub-field',
273                                                   help="When a relationship field is selected as first field, "
274                                                        "this field lets you select the target field within the "
275                                                        "destination document model (sub-model)."),
276         'null_value': fields.char('Default Value', help="Optional value to use if the target field is empty"),
277         'copyvalue': fields.char('Placeholder Expression', help="Final placeholder expression, to be copy-pasted in the desired template field."),
278     }
279
280     _defaults = {
281         'auto_delete': True,
282     }
283
284     def create_action(self, cr, uid, ids, context=None):
285         action_obj = self.pool.get('ir.actions.act_window')
286         data_obj = self.pool.get('ir.model.data')
287         for template in self.browse(cr, uid, ids, context=context):
288             src_obj = template.model_id.model
289             model_data_id = data_obj._get_id(cr, uid, 'mail', 'email_compose_message_wizard_form')
290             res_id = data_obj.browse(cr, uid, model_data_id, context=context).res_id
291             button_name = _('Send Mail (%s)') % template.name
292             act_id = action_obj.create(cr, SUPERUSER_ID, {
293                  'name': button_name,
294                  'type': 'ir.actions.act_window',
295                  'res_model': 'mail.compose.message',
296                  'src_model': src_obj,
297                  'view_type': 'form',
298                  'context': "{'default_composition_mode': 'mass_mail', 'default_template_id' : %d, 'default_use_template': True}" % (template.id),
299                  'view_mode':'form,tree',
300                  'view_id': res_id,
301                  'target': 'new',
302                  'auto_refresh':1
303             }, context)
304             ir_values_id = self.pool.get('ir.values').create(cr, SUPERUSER_ID, {
305                  'name': button_name,
306                  'model': src_obj,
307                  'key2': 'client_action_multi',
308                  'value': "ir.actions.act_window,%s" % act_id,
309                  'object': True,
310              }, context)
311
312             template.write({
313                 'ref_ir_act_window': act_id,
314                 'ref_ir_value': ir_values_id,
315             })
316
317         return True
318
319     def unlink_action(self, cr, uid, ids, context=None):
320         for template in self.browse(cr, uid, ids, context=context):
321             try:
322                 if template.ref_ir_act_window:
323                     self.pool.get('ir.actions.act_window').unlink(cr, SUPERUSER_ID, template.ref_ir_act_window.id, context)
324                 if template.ref_ir_value:
325                     ir_values_obj = self.pool.get('ir.values')
326                     ir_values_obj.unlink(cr, SUPERUSER_ID, template.ref_ir_value.id, context)
327             except Exception:
328                 raise osv.except_osv(_("Warning"), _("Deletion of the action record failed."))
329         return True
330
331     def unlink(self, cr, uid, ids, context=None):
332         self.unlink_action(cr, uid, ids, context=context)
333         return super(email_template, self).unlink(cr, uid, ids, context=context)
334
335     def copy(self, cr, uid, id, default=None, context=None):
336         template = self.browse(cr, uid, id, context=context)
337         if default is None:
338             default = {}
339         default = default.copy()
340         default.update(
341             name=_("%s (copy)") % (template.name),
342             ref_ir_act_window=False,
343             ref_ir_value=False)
344         return super(email_template, self).copy(cr, uid, id, default, context)
345
346     def build_expression(self, field_name, sub_field_name, null_value):
347         """Returns a placeholder expression for use in a template field,
348            based on the values provided in the placeholder assistant.
349
350           :param field_name: main field name
351           :param sub_field_name: sub field name (M2O)
352           :param null_value: default value if the target value is empty
353           :return: final placeholder expression
354         """
355         expression = ''
356         if field_name:
357             expression = "${object." + field_name
358             if sub_field_name:
359                 expression += "." + sub_field_name
360             if null_value:
361                 expression += " or '''%s'''" % null_value
362             expression += "}"
363         return expression
364
365     def onchange_sub_model_object_value_field(self, cr, uid, ids, model_object_field, sub_model_object_field=False, null_value=None, context=None):
366         result = {
367             'sub_object': False,
368             'copyvalue': False,
369             'sub_model_object_field': False,
370             'null_value': False
371             }
372         if model_object_field:
373             fields_obj = self.pool.get('ir.model.fields')
374             field_value = fields_obj.browse(cr, uid, model_object_field, context)
375             if field_value.ttype in ['many2one', 'one2many', 'many2many']:
376                 res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_value.relation)], context=context)
377                 sub_field_value = False
378                 if sub_model_object_field:
379                     sub_field_value = fields_obj.browse(cr, uid, sub_model_object_field, context)
380                 if res_ids:
381                     result.update({
382                         'sub_object': res_ids[0],
383                         'copyvalue': self.build_expression(field_value.name, sub_field_value and sub_field_value.name or False, null_value or False),
384                         'sub_model_object_field': sub_model_object_field or False,
385                         'null_value': null_value or False
386                         })
387             else:
388                 result.update({
389                         'copyvalue': self.build_expression(field_value.name, False, null_value or False),
390                         'null_value': null_value or False
391                         })
392         return {'value': result}
393
394     def generate_recipients_batch(self, cr, uid, results, template_id, res_ids, context=None):
395         """Generates the recipients of the template. Default values can ben generated
396         instead of the template values if requested by template or context.
397         Emails (email_to, email_cc) can be transformed into partners if requested
398         in the context. """
399         if context is None:
400             context = {}
401         template = self.browse(cr, uid, template_id, context=context)
402
403         if template.use_default_to or context.get('tpl_force_default_to'):
404             ctx = dict(context, thread_model=template.model)
405             default_recipients = self.pool['mail.thread'].message_get_default_recipients(cr, uid, res_ids, context=ctx)
406             for res_id, recipients in default_recipients.iteritems():
407                 results[res_id].pop('partner_to', None)
408                 results[res_id].update(recipients)
409
410         for res_id, values in results.iteritems():
411             partner_ids = values.get('partner_ids', list())
412             if context and context.get('tpl_partners_only'):
413                 mails = tools.email_split(values.pop('email_to', '')) + tools.email_split(values.pop('email_cc', ''))
414                 for mail in mails:
415                     partner_id = self.pool.get('res.partner').find_or_create(cr, uid, mail, context=context)
416                     partner_ids.append(partner_id)
417             partner_to = values.pop('partner_to', '')
418             if partner_to:
419                 # placeholders could generate '', 3, 2 due to some empty field values
420                 tpl_partner_ids = [pid for pid in partner_to.split(',') if pid]
421                 partner_ids += self.pool['res.partner'].exists(cr, SUPERUSER_ID, tpl_partner_ids, context=context)
422             results[res_id]['partner_ids'] = partner_ids
423         return results
424
425     def generate_email_batch(self, cr, uid, template_id, res_ids, context=None, fields=None):
426         """Generates an email from the template for given the given model based on
427         records given by res_ids.
428
429         :param template_id: id of the template to render.
430         :param res_id: id of the record to use for rendering the template (model
431                        is taken from template definition)
432         :returns: a dict containing all relevant fields for creating a new
433                   mail.mail entry, with one extra key ``attachments``, in the
434                   format [(report_name, data)] where data is base64 encoded.
435         """
436         if context is None:
437             context = {}
438         if fields is None:
439             fields = ['subject', 'body_html', 'email_from', 'email_to', 'partner_to', 'email_cc', 'reply_to']
440
441         report_xml_pool = self.pool.get('ir.actions.report.xml')
442         res_ids_to_templates = self.get_email_template_batch(cr, uid, template_id, res_ids, context)
443
444         # templates: res_id -> template; template -> res_ids
445         templates_to_res_ids = {}
446         for res_id, template in res_ids_to_templates.iteritems():
447             templates_to_res_ids.setdefault(template, []).append(res_id)
448
449         results = dict()
450         for template, template_res_ids in templates_to_res_ids.iteritems():
451             # generate fields value for all res_ids linked to the current template
452             for field in fields:
453                 generated_field_values = self.render_template_batch(
454                     cr, uid, getattr(template, field), template.model, template_res_ids,
455                     post_process=(field == 'body_html'),
456                     context=context)
457                 for res_id, field_value in generated_field_values.iteritems():
458                     results.setdefault(res_id, dict())[field] = field_value
459             # compute recipients
460             results = self.generate_recipients_batch(cr, uid, results, template.id, template_res_ids, context=context)
461             # update values for all res_ids
462             for res_id in template_res_ids:
463                 values = results[res_id]
464                 # body: add user signature, sanitize
465                 if 'body_html' in fields and template.user_signature:
466                     signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
467                     values['body_html'] = tools.append_content_to_html(values['body_html'], signature)
468                 if values.get('body_html'):
469                     values['body'] = tools.html_sanitize(values['body_html'])
470                 # technical settings
471                 values.update(
472                     mail_server_id=template.mail_server_id.id or False,
473                     auto_delete=template.auto_delete,
474                     model=template.model,
475                     res_id=res_id or False,
476                     attachment_ids=[attach.id for attach in template.attachment_ids],
477                 )
478
479             # Add report in attachments: generate once for all template_res_ids
480             if template.report_template:
481                 for res_id in template_res_ids:
482                     attachments = []
483                     report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context)
484                     report = report_xml_pool.browse(cr, uid, template.report_template.id, context)
485                     report_service = report.report_name
486                     # Ensure report is rendered using template's language
487                     ctx = context.copy()
488                     if template.lang:
489                         ctx['lang'] = self.render_template_batch(cr, uid, template.lang, template.model, [res_id], context)[res_id]  # take 0 ?
490
491                     if report.report_type in ['qweb-html', 'qweb-pdf']:
492                         result, format = self.pool['report'].get_pdf(cr, uid, [res_id], report_service, context=ctx), 'pdf'
493                     else:
494                         result, format = openerp.report.render_report(cr, uid, [res_id], report_service, {'model': template.model}, ctx)
495             
496                     # TODO in trunk, change return format to binary to match message_post expected format
497                     result = base64.b64encode(result)
498                     if not report_name:
499                         report_name = 'report.' + report_service
500                     ext = "." + format
501                     if not report_name.endswith(ext):
502                         report_name += ext
503                     attachments.append((report_name, result))
504                     results[res_id]['attachments'] = attachments
505
506         return results
507
508     def send_mail(self, cr, uid, template_id, res_id, force_send=False, raise_exception=False, context=None):
509         """Generates a new mail message for the given template and record,
510            and schedules it for delivery through the ``mail`` module's scheduler.
511
512            :param int template_id: id of the template to render
513            :param int res_id: id of the record to render the template with
514                               (model is taken from the template)
515            :param bool force_send: if True, the generated mail.message is
516                 immediately sent after being created, as if the scheduler
517                 was executed for this message only.
518            :returns: id of the mail.message that was created
519         """
520         if context is None:
521             context = {}
522         mail_mail = self.pool.get('mail.mail')
523         ir_attachment = self.pool.get('ir.attachment')
524
525         # create a mail_mail based on values, without attachments
526         values = self.generate_email(cr, uid, template_id, res_id, context=context)
527         if not values.get('email_from'):
528             raise osv.except_osv(_('Warning!'), _("Sender email is missing or empty after template rendering. Specify one to deliver your message"))
529         values['recipient_ids'] = [(4, pid) for pid in values.get('partner_ids', list())]
530         attachment_ids = values.pop('attachment_ids', [])
531         attachments = values.pop('attachments', [])
532         msg_id = mail_mail.create(cr, uid, values, context=context)
533         mail = mail_mail.browse(cr, uid, msg_id, context=context)
534
535         # manage attachments
536         for attachment in attachments:
537             attachment_data = {
538                 'name': attachment[0],
539                 'datas_fname': attachment[0],
540                 'datas': attachment[1],
541                 'res_model': 'mail.message',
542                 'res_id': mail.mail_message_id.id,
543             }
544             context.pop('default_type', None)
545             attachment_ids.append(ir_attachment.create(cr, uid, attachment_data, context=context))
546         if attachment_ids:
547             values['attachment_ids'] = [(6, 0, attachment_ids)]
548             mail_mail.write(cr, uid, msg_id, {'attachment_ids': [(6, 0, attachment_ids)]}, context=context)
549
550         if force_send:
551             mail_mail.send(cr, uid, [msg_id], raise_exception=raise_exception, context=context)
552         return msg_id
553
554     # Compatibility method
555     def render_template(self, cr, uid, template, model, res_id, context=None):
556         return self.render_template_batch(cr, uid, template, model, [res_id], context)[res_id]
557
558     def get_email_template(self, cr, uid, template_id=False, record_id=None, context=None):
559         return self.get_email_template_batch(cr, uid, template_id, [record_id], context)[record_id]
560
561     def generate_email(self, cr, uid, template_id, res_id, context=None):
562         return self.generate_email_batch(cr, uid, template_id, [res_id], context)[res_id]
563
564 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: