122501e5fea6aec54b03bf8d690f1cfc2f9f8fa6
[odoo/odoo.git] / addons / website / models / ir_ui_view.py
1 # -*- coding: utf-8 -*-
2 import copy
3
4 from lxml import etree, html
5
6 from openerp import SUPERUSER_ID, tools
7 from openerp.addons.website.models import website
8 from openerp.http import request
9 from openerp.osv import osv, fields
10
11 class view(osv.osv):
12     _inherit = "ir.ui.view"
13     _columns = {
14         'page': fields.boolean("Whether this view is a web page template (complete)"),
15         'website_meta_title': fields.char("Website meta title", size=70, translate=True),
16         'website_meta_description': fields.text("Website meta description", size=160, translate=True),
17         'website_meta_keywords': fields.char("Website meta keywords", translate=True),
18         'customize_show': fields.boolean("Show As Optional Inherit"),
19         'website_id': fields.many2one('website',ondelete='cascade', string="Website"),
20     }
21
22     _sql_constraints = [
23         ('key_website_id_uniq', 'unique(key, website_id)',
24             'Key must be unique per website.'),
25     ]
26
27     _defaults = {
28         'page': False,
29         'customize_show': False,
30     }
31
32     def _view_obj(self, cr, uid, view_id, context=None):
33         if isinstance(view_id, basestring):
34             return self.pool['ir.model.data'].xmlid_to_object(
35                 cr, uid, view_id, raise_if_not_found=True, context=context
36             )
37         elif isinstance(view_id, (int, long)):
38             return self.browse(cr, uid, view_id, context=context)
39
40         # assume it's already a view object (WTF?)
41         return view_id
42
43     # Returns all views (called and inherited) related to a view
44     # Used by translation mechanism, SEO and optional templates
45     def _views_get(self, cr, uid, view_id, options=True, bundles=False, context=None, root=True):
46         """ For a given view ``view_id``, should return:
47
48         * the view itself
49         * all views inheriting from it, enabled or not
50           - but not the optional children of a non-enabled child
51         * all views called from it (via t-call)
52         """
53         try:
54             view = self._view_obj(cr, uid, view_id, context=context)
55         except ValueError:
56             # Shall we log that ?
57             return []
58
59         while root and view.inherit_id:
60             view = view.inherit_id
61
62         result = [view]
63
64         node = etree.fromstring(view.arch)
65         xpath = "//t[@t-call]"
66         if bundles:
67             xpath += "| //t[@t-call-assets]"
68         for child in node.xpath(xpath):
69             try:
70                 called_view = self._view_obj(cr, uid, child.get('t-call', child.get('t-call-assets')), context=context)
71             except ValueError:
72                 continue
73             if called_view not in result:
74                 result += self._views_get(cr, uid, called_view, options=options, bundles=bundles, context=context)
75
76         extensions = view.inherit_children_ids
77         if not options:
78             # only active children
79             extensions = (v for v in view.inherit_children_ids if v.active)
80
81         # Keep options in a deterministic order regardless of their applicability
82         for extension in sorted(extensions, key=lambda v: v.id):
83             for r in self._views_get(
84                     cr, uid, extension,
85                     # only return optional grandchildren if this child is enabled
86                     options=extension.active,
87                     context=context, root=False):
88                 if r not in result:
89                     result.append(r)
90         return result
91
92     def extract_embedded_fields(self, cr, uid, arch, context=None):
93         return arch.xpath('//*[@data-oe-model != "ir.ui.view"]')
94
95     def save_embedded_field(self, cr, uid, el, context=None):
96         Model = self.pool[el.get('data-oe-model')]
97         field = el.get('data-oe-field')
98
99         converter = self.pool['website.qweb'].get_converter_for(el.get('data-oe-type'))
100         value = converter.from_html(cr, uid, Model, Model._fields[field], el)
101
102         if value is not None:
103             # TODO: batch writes?
104             Model.write(cr, uid, [int(el.get('data-oe-id'))], {
105                 field: value
106             }, context=context)
107
108     def to_field_ref(self, cr, uid, el, context=None):
109         # filter out meta-information inserted in the document
110         attributes = dict((k, v) for k, v in el.items()
111                           if not k.startswith('data-oe-'))
112         attributes['t-field'] = el.get('data-oe-expression')
113
114         out = html.html_parser.makeelement(el.tag, attrib=attributes)
115         out.tail = el.tail
116         return out
117
118     def replace_arch_section(self, cr, uid, view_id, section_xpath, replacement, context=None):
119         # the root of the arch section shouldn't actually be replaced as it's
120         # not really editable itself, only the content truly is editable.
121
122         [view] = self.browse(cr, uid, [view_id], context=context)
123         arch = etree.fromstring(view.arch.encode('utf-8'))
124         # => get the replacement root
125         if not section_xpath:
126             root = arch
127         else:
128             # ensure there's only one match
129             [root] = arch.xpath(section_xpath)
130
131         root.text = replacement.text
132         root.tail = replacement.tail
133         # replace all children
134         del root[:]
135         for child in replacement:
136             root.append(copy.deepcopy(child))
137
138         return arch
139
140     @tools.ormcache_context(accepted_keys=('website_id',))
141     def get_view_id(self, cr, uid, xml_id, context=None):
142         if context and 'website_id' in context and not isinstance(xml_id, (int, long)):
143             domain = [('key', '=', xml_id), '|', ('website_id', '=', context['website_id']), ('website_id', '=', False)]
144             [xml_id] = self.search(cr, uid, domain, order='website_id', limit=1, context=context)
145         else:
146             xml_id = super(view, self).get_view_id(cr, uid, xml_id, context=context)
147         return xml_id
148
149     def render(self, cr, uid, id_or_xml_id, values=None, engine='ir.qweb', context=None):
150         if request and getattr(request, 'website_enabled', False):
151             engine='website.qweb'
152
153             if isinstance(id_or_xml_id, list):
154                 id_or_xml_id = id_or_xml_id[0]
155
156             if not context:
157                 context = {}
158
159             company = self.pool['res.company'].browse(cr, SUPERUSER_ID, request.website.company_id.id, context=context)
160
161             qcontext = dict(
162                 context.copy(),
163                 website=request.website,
164                 url_for=website.url_for,
165                 slug=website.slug,
166                 res_company=company,
167                 user_id=self.pool.get("res.users").browse(cr, uid, uid),
168                 translatable=context.get('lang') != request.website.default_lang_code,
169                 editable=request.website.is_publisher(),
170                 menu_data=self.pool['ir.ui.menu'].load_menus_root(cr, uid, context=context) if request.website.is_user() else None,
171             )
172
173             # add some values
174             if values:
175                 qcontext.update(values)
176
177             # in edit mode ir.ui.view will tag nodes
178             if qcontext.get('editable'):
179                 context = dict(context, inherit_branding=True)
180             elif request.registry['res.users'].has_group(cr, uid, 'base.group_website_publisher'):
181                 context = dict(context, inherit_branding_auto=True)
182
183             view_obj = request.website.get_template(id_or_xml_id)
184             if 'main_object' not in qcontext:
185                 qcontext['main_object'] = view_obj
186
187             values = qcontext
188
189         return super(view, self).render(cr, uid, id_or_xml_id, values=values, engine=engine, context=context)
190
191     def _pretty_arch(self, arch):
192         # remove_blank_string does not seem to work on HTMLParser, and
193         # pretty-printing with lxml more or less requires stripping
194         # whitespace: http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output
195         # so serialize to XML, parse as XML (remove whitespace) then serialize
196         # as XML (pretty print)
197         arch_no_whitespace = etree.fromstring(
198             etree.tostring(arch, encoding='utf-8'),
199             parser=etree.XMLParser(encoding='utf-8', remove_blank_text=True))
200         return etree.tostring(
201             arch_no_whitespace, encoding='unicode', pretty_print=True)
202
203     def save(self, cr, uid, res_id, value, xpath=None, context=None):
204         """ Update a view section. The view section may embed fields to write
205
206         :param str model:
207         :param int res_id:
208         :param str xpath: valid xpath to the tag to replace
209         """
210         res_id = int(res_id)
211
212         arch_section = html.fromstring(
213             value, parser=html.HTMLParser(encoding='utf-8'))
214
215         if xpath is None:
216             # value is an embedded field on its own, not a view section
217             self.save_embedded_field(cr, uid, arch_section, context=context)
218             return
219
220         for el in self.extract_embedded_fields(cr, uid, arch_section, context=context):
221             self.save_embedded_field(cr, uid, el, context=context)
222
223             # transform embedded field back to t-field
224             el.getparent().replace(el, self.to_field_ref(cr, uid, el, context=context))
225
226         arch = self.replace_arch_section(cr, uid, res_id, xpath, arch_section, context=context)
227         self.write(cr, uid, res_id, {
228             'arch': self._pretty_arch(arch)
229         }, context=context)
230
231         view = self.browse(cr, SUPERUSER_ID, res_id, context=context)
232         if view.model_data_id:
233             view.model_data_id.write({'noupdate': True})
234