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