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