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