1 # -*- coding: utf-8 -*-
21 from xml.etree import ElementTree
22 from cStringIO import StringIO
24 import babel.messages.pofile
26 import werkzeug.wrappers
33 import openerp.modules.registry
34 from openerp.tools.translate import _
35 from openerp import http
37 from openerp.http import request, serialize_exception as _serialize_exception, LazyResponse
39 _logger = logging.getLogger(__name__)
41 env = jinja2.Environment(
42 loader=jinja2.PackageLoader('openerp.addons.web', "views"),
45 env.filters["json"] = simplejson.dumps
47 #----------------------------------------------------------
49 #----------------------------------------------------------
52 """ Minify js with a clever regex.
53 Taken from http://opensource.perlig.de/rjsmin
54 Apache License, Version 2.0 """
56 """ Substitution callback """
57 groups = match.groups()
63 (groups[4] and '\n') or
64 (groups[5] and ' ') or
65 (groups[6] and ' ') or
66 (groups[7] and ' ') or
71 r'([^\047"/\000-\040]+)|((?:(?:\047[^\047\\\r\n]*(?:\\(?:[^\r\n]|\r?'
72 r'\n|\r)[^\047\\\r\n]*)*\047)|(?:"[^"\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|'
73 r'\r)[^"\\\r\n]*)*"))[^\047"/\000-\040]*)|(?:(?<=[(,=:\[!&|?{};\r\n]'
74 r')(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/'
75 r'))*((?:/(?![\r\n/*])[^/\\\[\r\n]*(?:(?:\\[^\r\n]|(?:\[[^\\\]\r\n]*'
76 r'(?:\\[^\r\n][^\\\]\r\n]*)*\]))[^/\\\[\r\n]*)*/)[^\047"/\000-\040]*'
77 r'))|(?:(?<=[\000-#%-,./:-@\[-^`{-~-]return)(?:[\000-\011\013\014\01'
78 r'6-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*((?:/(?![\r\n/*])[^/'
79 r'\\\[\r\n]*(?:(?:\\[^\r\n]|(?:\[[^\\\]\r\n]*(?:\\[^\r\n][^\\\]\r\n]'
80 r'*)*\]))[^/\\\[\r\n]*)*/)[^\047"/\000-\040]*))|(?<=[^\000-!#%&(*,./'
81 r':-@\[\\^`{|~])(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/'
82 r'*][^*]*\*+)*/))*(?:((?:(?://[^\r\n]*)?[\r\n]))(?:[\000-\011\013\01'
83 r'4\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*)+(?=[^\000-\040"#'
84 r'%-\047)*,./:-@\\-^`|-~])|(?<=[^\000-#%-,./:-@\[-^`{-~-])((?:[\000-'
85 r'\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=[^'
86 r'\000-#%-,./:-@\[-^`{-~-])|(?<=\+)((?:[\000-\011\013\014\016-\040]|'
87 r'(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=\+)|(?<=-)((?:[\000-\011\0'
88 r'13\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=-)|(?:[\0'
89 r'00-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))+|(?:'
90 r'(?:(?://[^\r\n]*)?[\r\n])(?:[\000-\011\013\014\016-\040]|(?:/\*[^*'
91 r']*\*+(?:[^/*][^*]*\*+)*/))*)+', subber, '\n%s\n' % script
95 db_list = http.db_list
97 db_monodb = http.db_monodb
99 def serialize_exception(f):
101 def wrap(*args, **kwargs):
103 return f(*args, **kwargs)
105 _logger.exception("An exception occured during an http request")
106 se = _serialize_exception(e)
109 'message': "OpenERP Server Error",
112 return werkzeug.exceptions.InternalServerError(simplejson.dumps(error))
115 def redirect_with_hash(*args, **kw):
119 Use the ``http.redirect_with_hash()`` function instead.
121 return http.redirect_with_hash(*args, **kw)
123 def module_topological_sort(modules):
124 """ Return a list of module names sorted so that their dependencies of the
125 modules are listed before the module itself
127 modules is a dict of {module_name: dependencies}
129 :param modules: modules to sort
134 dependencies = set(itertools.chain.from_iterable(modules.itervalues()))
135 # incoming edge: dependency on other module (if a depends on b, a has an
136 # incoming edge from b, aka there's an edge from b to a)
137 # outgoing edge: other module depending on this one
139 # [Tarjan 1976], http://en.wikipedia.org/wiki/Topological_sorting#Algorithms
140 #L ← Empty list that will contain the sorted nodes
142 #S ← Set of all nodes with no outgoing edges (modules on which no other
144 S = set(module for module in modules if module not in dependencies)
147 #function visit(node n)
149 #if n has not been visited yet then
153 #change: n not web module, can not be resolved, ignore
154 if n not in modules: return
155 #for each node m with an edge from m to n do (dependencies of n)
161 #for each node n in S do
167 def module_installed():
168 # Candidates module the current heuristic is the /static dir
169 loadable = http.addons_manifest.keys()
172 # Retrieve database installed modules
173 # TODO The following code should move to ir.module.module.list_installed_modules()
174 Modules = request.session.model('ir.module.module')
175 domain = [('state','=','installed'), ('name','in', loadable)]
176 for module in Modules.search_read(domain, ['name', 'dependencies_id']):
177 modules[module['name']] = []
178 deps = module.get('dependencies_id')
180 deps_read = request.session.model('ir.module.module.dependency').read(deps, ['name'])
181 dependencies = [i['name'] for i in deps_read]
182 modules[module['name']] = dependencies
184 sorted_modules = module_topological_sort(modules)
185 return sorted_modules
187 def module_installed_bypass_session(dbname):
188 loadable = http.addons_manifest.keys()
191 registry = openerp.modules.registry.RegistryManager.get(dbname)
192 with registry.cursor() as cr:
193 m = registry.get('ir.module.module')
194 # TODO The following code should move to ir.module.module.list_installed_modules()
195 domain = [('state','=','installed'), ('name','in', loadable)]
196 ids = m.search(cr, 1, [('state','=','installed'), ('name','in', loadable)])
197 for module in m.read(cr, 1, ids, ['name', 'dependencies_id']):
198 modules[module['name']] = []
199 deps = module.get('dependencies_id')
201 deps_read = registry.get('ir.module.module.dependency').read(cr, 1, deps, ['name'])
202 dependencies = [i['name'] for i in deps_read]
203 modules[module['name']] = dependencies
206 sorted_modules = module_topological_sort(modules)
207 return sorted_modules
209 def module_boot(db=None):
210 server_wide_modules = openerp.conf.server_wide_modules or ['web']
213 for i in server_wide_modules:
214 if i in http.addons_manifest:
216 monodb = db or db_monodb()
218 dbside = module_installed_bypass_session(monodb)
219 dbside = [i for i in dbside if i not in serverside]
220 addons = serverside + dbside
223 def concat_xml(file_list):
224 """Concatenate xml files
226 :param list(str) file_list: list of files to check
227 :returns: (concatenation_result, checksum)
230 checksum = hashlib.new('sha1')
232 return '', checksum.hexdigest()
235 for fname in file_list:
236 with open(fname, 'rb') as fp:
238 checksum.update(contents)
240 xml = ElementTree.parse(fp).getroot()
243 root = ElementTree.Element(xml.tag)
244 #elif root.tag != xml.tag:
245 # raise ValueError("Root tags missmatch: %r != %r" % (root.tag, xml.tag))
247 for child in xml.getchildren():
249 return ElementTree.tostring(root, 'utf-8'), checksum.hexdigest()
251 def concat_files(file_list, reader=None, intersperse=""):
252 """ Concatenates contents of all provided files
254 :param list(str) file_list: list of files to check
255 :param function reader: reading procedure for each file
256 :param str intersperse: string to intersperse between file contents
257 :returns: (concatenation_result, checksum)
260 checksum = hashlib.new('sha1')
262 return '', checksum.hexdigest()
267 with codecs.open(f, 'rb', "utf-8-sig") as fp:
268 return fp.read().encode("utf-8")
271 for fname in file_list:
272 contents = reader(fname)
273 checksum.update(contents)
274 files_content.append(contents)
276 files_concat = intersperse.join(files_content)
277 return files_concat, checksum.hexdigest()
281 def concat_js(file_list):
282 content, checksum = concat_files(file_list, intersperse=';')
283 if checksum in concat_js_cache:
284 content = concat_js_cache[checksum]
286 content = rjsmin(content)
287 concat_js_cache[checksum] = content
288 return content, checksum
291 """convert FS path into web path"""
292 return '/'.join(path.split(os.path.sep))
294 def manifest_glob(extension, addons=None, db=None, include_remotes=False):
296 addons = module_boot(db=db)
298 addons = addons.split(',')
301 manifest = http.addons_manifest.get(addon, None)
304 # ensure does not ends with /
305 addons_path = os.path.join(manifest['addons_path'], '')[:-1]
306 globlist = manifest.get(extension, [])
307 for pattern in globlist:
308 if pattern.startswith(('http://', 'https://', '//')):
310 r.append((None, pattern))
312 for path in glob.glob(os.path.normpath(os.path.join(addons_path, addon, pattern))):
313 r.append((path, fs2web(path[len(addons_path):])))
316 def manifest_list(extension, mods=None, db=None, debug=False):
317 """ list ressources to load specifying either:
318 mods: a comma separated string listing modules
319 db: a database name (return all installed modules in that database)
321 files = manifest_glob(extension, addons=mods, db=db, include_remotes=True)
323 path = '/web/webclient/' + extension
325 path += '?' + urllib.urlencode({'mods': mods})
327 path += '?' + urllib.urlencode({'db': db})
329 remotes = [wp for fp, wp in files if fp is None]
330 return [path] + remotes
331 return [wp for _fp, wp in files]
333 def get_last_modified(files):
334 """ Returns the modification time of the most recently modified
337 :param list(str) files: names of files to check
338 :return: most recent modification time amongst the fileset
339 :rtype: datetime.datetime
343 return max(datetime.datetime.fromtimestamp(os.path.getmtime(f))
345 return datetime.datetime(1970, 1, 1)
347 def make_conditional(response, last_modified=None, etag=None):
348 """ Makes the provided response conditional based upon the request,
349 and mandates revalidation from clients
351 Uses Werkzeug's own :meth:`ETagResponseMixin.make_conditional`, after
352 setting ``last_modified`` and ``etag`` correctly on the response object
354 :param response: Werkzeug response
355 :type response: werkzeug.wrappers.Response
356 :param datetime.datetime last_modified: last modification date of the response content
357 :param str etag: some sort of checksum of the content (deep etag)
358 :return: the response object provided
359 :rtype: werkzeug.wrappers.Response
361 response.cache_control.must_revalidate = True
362 response.cache_control.max_age = 0
364 response.last_modified = last_modified
366 response.set_etag(etag)
367 return response.make_conditional(request.httprequest)
369 def login_and_redirect(db, login, key, redirect_url='/web'):
370 request.session.authenticate(db, login, key)
371 return set_cookie_and_redirect(redirect_url)
373 def set_cookie_and_redirect(redirect_url):
374 redirect = werkzeug.utils.redirect(redirect_url, 303)
375 redirect.autocorrect_location_header = False
378 def load_actions_from_ir_values(key, key2, models, meta):
379 Values = request.session.model('ir.values')
380 actions = Values.get(key, key2, models, meta, request.context)
382 return [(id, name, clean_action(action))
383 for id, name, action in actions]
385 def clean_action(action):
386 action.setdefault('flags', {})
387 action_type = action.setdefault('type', 'ir.actions.act_window_close')
388 if action_type == 'ir.actions.act_window':
389 return fix_view_modes(action)
392 # I think generate_views,fix_view_modes should go into js ActionManager
393 def generate_views(action):
395 While the server generates a sequence called "views" computing dependencies
396 between a bunch of stuff for views coming directly from the database
397 (the ``ir.actions.act_window model``), it's also possible for e.g. buttons
398 to return custom view dictionaries generated on the fly.
400 In that case, there is no ``views`` key available on the action.
402 Since the web client relies on ``action['views']``, generate it here from
403 ``view_mode`` and ``view_id``.
405 Currently handles two different cases:
407 * no view_id, multiple view_mode
408 * single view_id, single view_mode
410 :param dict action: action descriptor dictionary to generate a views key for
412 view_id = action.get('view_id') or False
413 if isinstance(view_id, (list, tuple)):
416 # providing at least one view mode is a requirement, not an option
417 view_modes = action['view_mode'].split(',')
419 if len(view_modes) > 1:
421 raise ValueError('Non-db action dictionaries should provide '
422 'either multiple view modes or a single view '
423 'mode and an optional view id.\n\n Got view '
424 'modes %r and view id %r for action %r' % (
425 view_modes, view_id, action))
426 action['views'] = [(False, mode) for mode in view_modes]
428 action['views'] = [(view_id, view_modes[0])]
430 def fix_view_modes(action):
431 """ For historical reasons, OpenERP has weird dealings in relation to
432 view_mode and the view_type attribute (on window actions):
434 * one of the view modes is ``tree``, which stands for both list views
436 * the choice is made by checking ``view_type``, which is either
437 ``form`` for a list view or ``tree`` for an actual tree view
439 This methods simply folds the view_type into view_mode by adding a
440 new view mode ``list`` which is the result of the ``tree`` view_mode
441 in conjunction with the ``form`` view_type.
443 TODO: this should go into the doc, some kind of "peculiarities" section
445 :param dict action: an action descriptor
446 :returns: nothing, the action is modified in place
448 if not action.get('views'):
449 generate_views(action)
451 if action.pop('view_type', 'form') != 'form':
454 if 'view_mode' in action:
455 action['view_mode'] = ','.join(
456 mode if mode != 'tree' else 'list'
457 for mode in action['view_mode'].split(','))
459 [id, mode if mode != 'tree' else 'list']
460 for id, mode in action['views']
465 def _local_web_translations(trans_file):
468 with open(trans_file) as t_file:
469 po = babel.messages.pofile.read_po(t_file)
473 if x.id and x.string and "openerp-web" in x.auto_comments:
474 messages.append({'id': x.id, 'string': x.string})
477 def xml2json_from_elementtree(el, preserve_whitespaces=False):
479 Simple and straightforward XML-to-JSON converter in Python
481 http://code.google.com/p/xml2json-direct/
485 ns, name = el.tag.rsplit("}", 1)
487 res["namespace"] = ns[1:]
491 for k, v in el.items():
494 if el.text and (preserve_whitespaces or el.text.strip() != ''):
497 kids.append(xml2json_from_elementtree(kid, preserve_whitespaces))
498 if kid.tail and (preserve_whitespaces or kid.tail.strip() != ''):
499 kids.append(kid.tail)
500 res["children"] = kids
503 def content_disposition(filename):
504 filename = filename.encode('utf8')
505 escaped = urllib2.quote(filename)
506 browser = request.httprequest.user_agent.browser
507 version = int((request.httprequest.user_agent.version or '0').split('.')[0])
508 if browser == 'msie' and version < 9:
509 return "attachment; filename=%s" % escaped
510 elif browser == 'safari':
511 return "attachment; filename=%s" % filename
513 return "attachment; filename*=UTF-8''%s" % escaped
516 #----------------------------------------------------------
517 # OpenERP Web web Controllers
518 #----------------------------------------------------------
520 # TODO: to remove once the database manager has been migrated server side
521 # and `edi` + `pos` addons has been adapted to use render_bootstrap_template()
522 html_template = """<!DOCTYPE html>
523 <html style="height: 100%%">
525 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
526 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
527 <title>OpenERP</title>
528 <link rel="shortcut icon" href="/web/static/src/img/favicon.ico" type="image/x-icon"/>
529 <link rel="stylesheet" href="/web/static/src/css/full.css" />
532 <script type="text/javascript">
534 var s = new openerp.init(%(modules)s);
541 <script src="//ajax.googleapis.com/ajax/libs/chrome-frame/1/CFInstall.min.js"></script>
542 <script>CFInstall.check({mode: "overlay"});</script>
548 def render_bootstrap_template(db, template, values=None, debug=False, lazy=False, **kw):
549 if request and request.debug:
554 values['debug'] = debug
555 values['current_db'] = db
557 values['databases'] = http.db_list()
558 except openerp.exceptions.AccessDenied:
559 values['databases'] = None
561 for res in ['js', 'css']:
562 if res not in values:
563 values[res] = manifest_list(res, db=db, debug=debug)
565 if 'modules' not in values:
566 values['modules'] = module_boot(db=db)
567 values['modules'] = simplejson.dumps(values['modules'])
569 def callback(template, values):
570 registry = openerp.modules.registry.RegistryManager.get(db)
571 with registry.cursor() as cr:
572 view_obj = registry["ir.ui.view"]
573 return view_obj.render(cr, openerp.SUPERUSER_ID, template, values)
575 return LazyResponse(callback, template=template, values=values)
577 return callback(template, values)
579 class Home(http.Controller):
581 @http.route('/', type='http', auth="none")
582 def index(self, s_action=None, db=None, **kw):
583 return http.local_redirect('/web', query=request.params)
585 @http.route('/web', type='http', auth="none")
586 def web_client(self, s_action=None, **kw):
589 if request.session.uid:
590 html = render_bootstrap_template(request.session.db, "web.webclient_bootstrap")
591 return request.make_response(html, {'Cache-Control': 'no-cache', 'Content-Type': 'text/html; charset=utf-8'})
593 return http.local_redirect('/web/login', query=request.params)
595 @http.route('/web/login', type='http', auth="none")
596 def web_login(self, redirect=None, **kw):
597 http.ensure_db(with_registry=True)
599 values = request.params.copy()
601 redirect = '/web?' + request.httprequest.query_string
602 values['redirect'] = redirect
603 if request.httprequest.method == 'POST':
604 uid = request.session.authenticate(request.session.db, request.params['login'], request.params['password'])
606 return http.redirect_with_hash(redirect)
607 values['error'] = "Wrong login/password"
608 return render_bootstrap_template(request.session.db, 'web.login', values, lazy=True)
610 @http.route('/login', type='http', auth="none")
611 def login(self, db, login, key, redirect="/web", **kw):
612 return login_and_redirect(db, login, key, redirect_url=redirect)
614 class WebClient(http.Controller):
616 @http.route('/web/webclient/csslist', type='json', auth="none")
617 def csslist(self, mods=None):
618 return manifest_list('css', mods=mods)
620 @http.route('/web/webclient/jslist', type='json', auth="none")
621 def jslist(self, mods=None):
622 return manifest_list('js', mods=mods)
624 @http.route('/web/webclient/qweblist', type='json', auth="none")
625 def qweblist(self, mods=None):
626 return manifest_list('qweb', mods=mods)
628 @http.route('/web/webclient/css', type='http', auth="none")
629 def css(self, mods=None, db=None):
630 files = list(manifest_glob('css', addons=mods, db=db))
631 last_modified = get_last_modified(f[0] for f in files)
632 if request.httprequest.if_modified_since and request.httprequest.if_modified_since >= last_modified:
633 return werkzeug.wrappers.Response(status=304)
635 file_map = dict(files)
637 rx_import = re.compile(r"""@import\s+('|")(?!'|"|/|https?://)""", re.U)
638 rx_url = re.compile(r"""url\s*\(\s*('|"|)(?!'|"|/|https?://|data:)""", re.U)
641 """read the a css file and absolutify all relative uris"""
642 with open(f, 'rb') as fp:
643 data = fp.read().decode('utf-8')
646 web_dir = os.path.dirname(path)
650 r"""@import \1%s/""" % (web_dir,),
656 r"url(\1%s/" % (web_dir,),
659 return data.encode('utf-8')
661 content, checksum = concat_files((f[0] for f in files), reader)
663 # move up all @import and @charset rules to the top
666 matches.append(matchobj.group(0))
669 content = re.sub(re.compile("(@charset.+;$)", re.M), push, content)
670 content = re.sub(re.compile("(@import.+;$)", re.M), push, content)
672 matches.append(content)
673 content = '\n'.join(matches)
675 return make_conditional(
676 request.make_response(content, [('Content-Type', 'text/css')]),
677 last_modified, checksum)
679 @http.route('/web/webclient/js', type='http', auth="none")
680 def js(self, mods=None, db=None):
681 files = [f[0] for f in manifest_glob('js', addons=mods, db=db)]
682 last_modified = get_last_modified(files)
683 if request.httprequest.if_modified_since and request.httprequest.if_modified_since >= last_modified:
684 return werkzeug.wrappers.Response(status=304)
686 content, checksum = concat_js(files)
688 return make_conditional(
689 request.make_response(content, [('Content-Type', 'application/javascript')]),
690 last_modified, checksum)
692 @http.route('/web/webclient/qweb', type='http', auth="none")
693 def qweb(self, mods=None, db=None):
694 files = [f[0] for f in manifest_glob('qweb', addons=mods, db=db)]
695 last_modified = get_last_modified(files)
696 if request.httprequest.if_modified_since and request.httprequest.if_modified_since >= last_modified:
697 return werkzeug.wrappers.Response(status=304)
699 content, checksum = concat_xml(files)
701 return make_conditional(
702 request.make_response(content, [('Content-Type', 'text/xml')]),
703 last_modified, checksum)
705 @http.route('/web/webclient/bootstrap_translations', type='json', auth="none")
706 def bootstrap_translations(self, mods):
707 """ Load local translations from *.po files, as a temporary solution
708 until we have established a valid session. This is meant only
709 for translating the login page and db management chrome, using
710 the browser's language. """
711 # For performance reasons we only load a single translation, so for
712 # sub-languages (that should only be partially translated) we load the
713 # main language PO instead - that should be enough for the login screen.
714 lang = request.lang.split('_')[0]
716 translations_per_module = {}
717 for addon_name in mods:
718 if http.addons_manifest[addon_name].get('bootstrap'):
719 addons_path = http.addons_manifest[addon_name]['addons_path']
720 f_name = os.path.join(addons_path, addon_name, "i18n", lang + ".po")
721 if not os.path.exists(f_name):
723 translations_per_module[addon_name] = {'messages': _local_web_translations(f_name)}
725 return {"modules": translations_per_module,
726 "lang_parameters": None}
728 @http.route('/web/webclient/translations', type='json', auth="none")
729 def translations(self, mods=None, lang=None):
730 request.disable_db = False
731 uid = openerp.SUPERUSER_ID
733 m = request.registry.get('ir.module.module')
734 mods = [x['name'] for x in m.search_read(request.cr, uid,
735 [('state','=','installed')], ['name'])]
737 lang = request.context["lang"]
738 res_lang = request.registry.get('res.lang')
739 ids = res_lang.search(request.cr, uid, [("code", "=", lang)])
742 lang_params = res_lang.read(request.cr, uid, ids[0], ["direction", "date_format", "time_format",
743 "grouping", "decimal_point", "thousands_sep"])
745 # Regional languages (ll_CC) must inherit/override their parent lang (ll), but this is
746 # done server-side when the language is loaded, so we only need to load the user's lang.
747 ir_translation = request.registry.get('ir.translation')
748 translations_per_module = {}
749 messages = ir_translation.search_read(request.cr, uid, [('module','in',mods),('lang','=',lang),
750 ('comments','like','openerp-web'),('value','!=',False),
752 ['module','src','value','lang'], order='module')
753 for mod, msg_group in itertools.groupby(messages, key=operator.itemgetter('module')):
754 translations_per_module.setdefault(mod,{'messages':[]})
755 translations_per_module[mod]['messages'].extend({'id': m['src'],
756 'string': m['value']} \
758 return {"modules": translations_per_module,
759 "lang_parameters": lang_params}
761 @http.route('/web/webclient/version_info', type='json', auth="none")
762 def version_info(self):
763 return openerp.service.common.exp_version()
765 class Proxy(http.Controller):
767 @http.route('/web/proxy/load', type='json', auth="none")
768 def load(self, path):
769 """ Proxies an HTTP request through a JSON request.
771 It is strongly recommended to not request binary files through this,
772 as the result will be a binary data blob as well.
774 :param path: actual request path
775 :return: file content
777 from werkzeug.test import Client
778 from werkzeug.wrappers import BaseResponse
780 return Client(request.httprequest.app, BaseResponse).get(path).data
782 class Database(http.Controller):
784 @http.route('/web/database/selector', type='http', auth="none")
785 def selector(self, **kw):
789 return http.local_redirect('/web/database/manager')
790 except openerp.exceptions.AccessDenied:
792 return env.get_template("database_selector.html").render({
794 'debug': request.debug,
797 @http.route('/web/database/manager', type='http', auth="none")
798 def manager(self, **kw):
799 # TODO: migrate the webclient's database manager to server side views
800 request.session.logout()
801 js = "\n ".join('<script type="text/javascript" src="%s"></script>' % i for i in manifest_list('js', debug=request.debug))
802 css = "\n ".join('<link rel="stylesheet" href="%s">' % i for i in manifest_list('css', debug=request.debug))
804 r = html_template % {
807 'modules': simplejson.dumps(module_boot()),
809 var wc = new s.web.WebClient(null, { action: 'database_manager' });
810 wc.appendTo($(document.body));
815 @http.route('/web/database/get_list', type='json', auth="none")
817 # TODO change js to avoid calling this method if in monodb mode
819 return http.db_list()
820 except openerp.exceptions.AccessDenied:
826 @http.route('/web/database/create', type='json', auth="none")
827 def create(self, fields):
828 params = dict(map(operator.itemgetter('name', 'value'), fields))
829 db_created = request.session.proxy("db").create_database(
830 params['super_admin_pwd'],
832 bool(params.get('demo_data')),
834 params['create_admin_pwd'])
836 request.session.authenticate(params['db_name'], 'admin', params['create_admin_pwd'])
839 @http.route('/web/database/duplicate', type='json', auth="none")
840 def duplicate(self, fields):
841 params = dict(map(operator.itemgetter('name', 'value'), fields))
843 params['super_admin_pwd'],
844 params['db_original_name'],
848 return request.session.proxy("db").duplicate_database(*duplicate_attrs)
850 @http.route('/web/database/drop', type='json', auth="none")
851 def drop(self, fields):
852 password, db = operator.itemgetter(
853 'drop_pwd', 'drop_db')(
854 dict(map(operator.itemgetter('name', 'value'), fields)))
857 if request.session.proxy("db").drop(password, db):
861 except openerp.exceptions.AccessDenied:
862 return {'error': 'AccessDenied', 'title': 'Drop Database'}
864 return {'error': _('Could not drop database !'), 'title': _('Drop Database')}
866 @http.route('/web/database/backup', type='http', auth="none")
867 def backup(self, backup_db, backup_pwd, token):
869 db_dump = base64.b64decode(
870 request.session.proxy("db").dump(backup_pwd, backup_db))
871 filename = "%(db)s_%(timestamp)s.dump" % {
873 'timestamp': datetime.datetime.utcnow().strftime(
874 "%Y-%m-%d_%H-%M-%SZ")
876 return request.make_response(db_dump,
877 [('Content-Type', 'application/octet-stream; charset=binary'),
878 ('Content-Disposition', content_disposition(filename))],
882 return simplejson.dumps([[],[{'error': openerp.tools.ustr(e), 'title': _('Backup Database')}]])
884 @http.route('/web/database/restore', type='http', auth="none")
885 def restore(self, db_file, restore_pwd, new_db):
887 data = base64.b64encode(db_file.read())
888 request.session.proxy("db").restore(restore_pwd, new_db, data)
890 except openerp.exceptions.AccessDenied, e:
891 raise Exception("AccessDenied")
893 @http.route('/web/database/change_password', type='json', auth="none")
894 def change_password(self, fields):
895 old_password, new_password = operator.itemgetter(
896 'old_pwd', 'new_pwd')(
897 dict(map(operator.itemgetter('name', 'value'), fields)))
899 return request.session.proxy("db").change_admin_password(old_password, new_password)
900 except openerp.exceptions.AccessDenied:
901 return {'error': 'AccessDenied', 'title': _('Change Password')}
903 return {'error': _('Error, password not changed !'), 'title': _('Change Password')}
905 class Session(http.Controller):
907 def session_info(self):
908 request.session.ensure_valid()
910 "session_id": request.session_id,
911 "uid": request.session.uid,
912 "user_context": request.session.get_context() if request.session.uid else {},
913 "db": request.session.db,
914 "username": request.session.login,
917 @http.route('/web/session/get_session_info', type='json', auth="none")
918 def get_session_info(self):
919 request.uid = request.session.uid
920 request.disable_db = False
921 return self.session_info()
923 @http.route('/web/session/authenticate', type='json', auth="none")
924 def authenticate(self, db, login, password, base_location=None):
925 request.session.authenticate(db, login, password)
927 return self.session_info()
929 @http.route('/web/session/change_password', type='json', auth="user")
930 def change_password(self, fields):
931 old_password, new_password,confirm_password = operator.itemgetter('old_pwd', 'new_password','confirm_pwd')(
932 dict(map(operator.itemgetter('name', 'value'), fields)))
933 if not (old_password.strip() and new_password.strip() and confirm_password.strip()):
934 return {'error':_('You cannot leave any password empty.'),'title': _('Change Password')}
935 if new_password != confirm_password:
936 return {'error': _('The new password and its confirmation must be identical.'),'title': _('Change Password')}
938 if request.session.model('res.users').change_password(
939 old_password, new_password):
940 return {'new_password':new_password}
942 return {'error': _('The old password you provided is incorrect, your password was not changed.'), 'title': _('Change Password')}
943 return {'error': _('Error, password not changed !'), 'title': _('Change Password')}
945 @http.route('/web/session/get_lang_list', type='json', auth="none")
946 def get_lang_list(self):
948 return request.session.proxy("db").list_lang() or []
950 return {"error": e, "title": _("Languages")}
952 @http.route('/web/session/modules', type='json', auth="user")
954 # return all installed modules. Web client is smart enough to not load a module twice
955 return module_installed()
957 @http.route('/web/session/save_session_action', type='json', auth="user")
958 def save_session_action(self, the_action):
960 This method store an action object in the session object and returns an integer
961 identifying that action. The method get_session_action() can be used to get
964 :param the_action: The action to save in the session.
965 :type the_action: anything
966 :return: A key identifying the saved action.
969 saved_actions = request.httpsession.get('saved_actions')
970 if not saved_actions:
971 saved_actions = {"next":1, "actions":{}}
972 request.httpsession['saved_actions'] = saved_actions
973 # we don't allow more than 10 stored actions
974 if len(saved_actions["actions"]) >= 10:
975 del saved_actions["actions"][min(saved_actions["actions"])]
976 key = saved_actions["next"]
977 saved_actions["actions"][key] = the_action
978 saved_actions["next"] = key + 1
981 @http.route('/web/session/get_session_action', type='json', auth="user")
982 def get_session_action(self, key):
984 Gets back a previously saved action. This method can return None if the action
985 was saved since too much time (this case should be handled in a smart way).
987 :param key: The key given by save_session_action()
989 :return: The saved action or None.
992 saved_actions = request.httpsession.get('saved_actions')
993 if not saved_actions:
995 return saved_actions["actions"].get(key)
997 @http.route('/web/session/check', type='json', auth="user")
999 request.session.assert_valid()
1002 @http.route('/web/session/destroy', type='json', auth="user")
1004 request.session.logout()
1006 @http.route('/web/session/logout', type='http', auth="none")
1007 def logout(self, redirect='/web'):
1008 request.session.logout(keep_db=True)
1009 return werkzeug.utils.redirect(redirect, 303)
1011 class Menu(http.Controller):
1013 @http.route('/web/menu/get_user_roots', type='json', auth="user")
1014 def get_user_roots(self):
1015 """ Return all root menu ids visible for the session user.
1017 :return: the root menu ids
1021 Menus = s.model('ir.ui.menu')
1022 # If a menu action is defined use its domain to get the root menu items
1023 user_menu_id = s.model('res.users').read([s.uid], ['menu_id'],
1024 request.context)[0]['menu_id']
1026 menu_domain = [('parent_id', '=', False)]
1028 domain_string = s.model('ir.actions.act_window').read(
1029 [user_menu_id[0]], ['domain'],request.context)[0]['domain']
1031 menu_domain = ast.literal_eval(domain_string)
1033 return Menus.search(menu_domain, 0, False, False, request.context)
1035 @http.route('/web/menu/load', type='json', auth="user")
1037 """ Loads all menu items (all applications and their sub-menus).
1039 :return: the menu root
1040 :rtype: dict('children': menu_nodes)
1042 Menus = request.session.model('ir.ui.menu')
1044 fields = ['name', 'sequence', 'parent_id', 'action']
1045 menu_root_ids = self.get_user_roots()
1046 menu_roots = Menus.read(menu_root_ids, fields, request.context) if menu_root_ids else []
1050 'parent_id': [-1, ''],
1051 'children': menu_roots,
1052 'all_menu_ids': menu_root_ids,
1057 # menus are loaded fully unlike a regular tree view, cause there are a
1058 # limited number of items (752 when all 6.1 addons are installed)
1059 menu_ids = Menus.search([('id', 'child_of', menu_root_ids)], 0, False, False, request.context)
1060 menu_items = Menus.read(menu_ids, fields, request.context)
1061 # adds roots at the end of the sequence, so that they will overwrite
1062 # equivalent menu items from full menu read when put into id:item
1063 # mapping, resulting in children being correctly set on the roots.
1064 menu_items.extend(menu_roots)
1065 menu_root['all_menu_ids'] = menu_ids # includes menu_root_ids!
1067 # make a tree using parent_id
1068 menu_items_map = dict(
1069 (menu_item["id"], menu_item) for menu_item in menu_items)
1070 for menu_item in menu_items:
1071 if menu_item['parent_id']:
1072 parent = menu_item['parent_id'][0]
1075 if parent in menu_items_map:
1076 menu_items_map[parent].setdefault(
1077 'children', []).append(menu_item)
1079 # sort by sequence a tree using parent_id
1080 for menu_item in menu_items:
1081 menu_item.setdefault('children', []).sort(
1082 key=operator.itemgetter('sequence'))
1086 @http.route('/web/menu/load_needaction', type='json', auth="user")
1087 def load_needaction(self, menu_ids):
1088 """ Loads needaction counters for specific menu ids.
1090 :return: needaction data
1091 :rtype: dict(menu_id: {'needaction_enabled': boolean, 'needaction_counter': int})
1093 return request.session.model('ir.ui.menu').get_needaction_data(menu_ids, request.context)
1095 class DataSet(http.Controller):
1097 @http.route('/web/dataset/search_read', type='json', auth="user")
1098 def search_read(self, model, fields=False, offset=0, limit=False, domain=None, sort=None):
1099 return self.do_search_read(model, fields, offset, limit, domain, sort)
1100 def do_search_read(self, model, fields=False, offset=0, limit=False, domain=None
1102 """ Performs a search() followed by a read() (if needed) using the
1103 provided search criteria
1105 :param str model: the name of the model to search on
1106 :param fields: a list of the fields to return in the result records
1108 :param int offset: from which index should the results start being returned
1109 :param int limit: the maximum number of records to return
1110 :param list domain: the search domain for the query
1111 :param list sort: sorting directives
1112 :returns: A structure (dict) with two keys: ids (all the ids matching
1113 the (domain, context) pair) and records (paginated records
1114 matching fields selection set)
1117 Model = request.session.model(model)
1119 ids = Model.search(domain, offset or 0, limit or False, sort or False,
1121 if limit and len(ids) == limit:
1122 length = Model.search_count(domain, request.context)
1124 length = len(ids) + (offset or 0)
1125 if fields and fields == ['id']:
1126 # shortcut read if we only want the ids
1129 'records': [{'id': id} for id in ids]
1132 records = Model.read(ids, fields or False, request.context)
1133 records.sort(key=lambda obj: ids.index(obj['id']))
1139 @http.route('/web/dataset/load', type='json', auth="user")
1140 def load(self, model, id, fields):
1141 m = request.session.model(model)
1143 r = m.read([id], False, request.context)
1146 return {'value': value}
1148 def call_common(self, model, method, args, domain_id=None, context_id=None):
1149 return self._call_kw(model, method, args, {})
1151 def _call_kw(self, model, method, args, kwargs):
1152 # Temporary implements future display_name special field for model#read()
1153 if method == 'read' and kwargs.get('context', {}).get('future_display_name'):
1154 if 'display_name' in args[1]:
1155 names = dict(request.session.model(model).name_get(args[0], **kwargs))
1156 args[1].remove('display_name')
1157 records = request.session.model(model).read(*args, **kwargs)
1158 for record in records:
1159 record['display_name'] = \
1160 names.get(record['id']) or "%s#%d" % (model, (record['id']))
1163 if method.startswith('_'):
1164 raise Exception("Access Denied: Underscore prefixed methods cannot be remotely called")
1166 return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
1168 @http.route('/web/dataset/call', type='json', auth="user")
1169 def call(self, model, method, args, domain_id=None, context_id=None):
1170 return self._call_kw(model, method, args, {})
1172 @http.route(['/web/dataset/call_kw', '/web/dataset/call_kw/<path:path>'], type='json', auth="user")
1173 def call_kw(self, model, method, args, kwargs, path=None):
1174 return self._call_kw(model, method, args, kwargs)
1176 @http.route('/web/dataset/call_button', type='json', auth="user")
1177 def call_button(self, model, method, args, domain_id=None, context_id=None):
1178 action = self._call_kw(model, method, args, {})
1179 if isinstance(action, dict) and action.get('type') != '':
1180 return clean_action(action)
1183 @http.route('/web/dataset/exec_workflow', type='json', auth="user")
1184 def exec_workflow(self, model, id, signal):
1185 return request.session.exec_workflow(model, id, signal)
1187 @http.route('/web/dataset/resequence', type='json', auth="user")
1188 def resequence(self, model, ids, field='sequence', offset=0):
1189 """ Re-sequences a number of records in the model, by their ids
1191 The re-sequencing starts at the first model of ``ids``, the sequence
1192 number is incremented by one after each record and starts at ``offset``
1194 :param ids: identifiers of the records to resequence, in the new sequence order
1196 :param str field: field used for sequence specification, defaults to
1198 :param int offset: sequence number for first record in ``ids``, allows
1199 starting the resequencing from an arbitrary number,
1202 m = request.session.model(model)
1203 if not m.fields_get([field]):
1205 # python 2.6 has no start parameter
1206 for i, id in enumerate(ids):
1207 m.write(id, { field: i + offset })
1210 class View(http.Controller):
1212 @http.route('/web/view/add_custom', type='json', auth="user")
1213 def add_custom(self, view_id, arch):
1214 CustomView = request.session.model('ir.ui.view.custom')
1216 'user_id': request.session.uid,
1220 return {'result': True}
1222 @http.route('/web/view/undo_custom', type='json', auth="user")
1223 def undo_custom(self, view_id, reset=False):
1224 CustomView = request.session.model('ir.ui.view.custom')
1225 vcustom = CustomView.search([('user_id', '=', request.session.uid), ('ref_id' ,'=', view_id)],
1226 0, False, False, request.context)
1229 CustomView.unlink(vcustom, request.context)
1231 CustomView.unlink([vcustom[0]], request.context)
1232 return {'result': True}
1233 return {'result': False}
1235 class TreeView(View):
1237 @http.route('/web/treeview/action', type='json', auth="user")
1238 def action(self, model, id):
1239 return load_actions_from_ir_values(
1240 'action', 'tree_but_open',[(model, id)],
1243 class Binary(http.Controller):
1245 @http.route('/web/binary/image', type='http', auth="user")
1246 def image(self, model, id, field, **kw):
1247 last_update = '__last_update'
1248 Model = request.session.model(model)
1249 headers = [('Content-Type', 'image/png')]
1250 etag = request.httprequest.headers.get('If-None-Match')
1251 hashed_session = hashlib.md5(request.session_id).hexdigest()
1252 retag = hashed_session
1253 id = None if not id else simplejson.loads(id)
1254 if type(id) is list:
1258 if not id and hashed_session == etag:
1259 return werkzeug.wrappers.Response(status=304)
1261 date = Model.read([id], [last_update], request.context)[0].get(last_update)
1262 if hashlib.md5(date).hexdigest() == etag:
1263 return werkzeug.wrappers.Response(status=304)
1266 res = Model.default_get([field], request.context).get(field)
1269 res = Model.read([id], [last_update, field], request.context)[0]
1270 retag = hashlib.md5(res.get(last_update)).hexdigest()
1271 image_base64 = res.get(field)
1273 if kw.get('resize'):
1274 resize = kw.get('resize').split(',')
1275 if len(resize) == 2 and int(resize[0]) and int(resize[1]):
1276 width = int(resize[0])
1277 height = int(resize[1])
1278 # resize maximum 500*500
1279 if width > 500: width = 500
1280 if height > 500: height = 500
1281 image_base64 = openerp.tools.image_resize_image(base64_source=image_base64, size=(width, height), encoding='base64', filetype='PNG')
1283 image_data = base64.b64decode(image_base64)
1286 image_data = self.placeholder()
1287 headers.append(('ETag', retag))
1288 headers.append(('Content-Length', len(image_data)))
1290 ncache = int(kw.get('cache'))
1291 headers.append(('Cache-Control', 'no-cache' if ncache == 0 else 'max-age=%s' % (ncache)))
1294 return request.make_response(image_data, headers)
1296 def placeholder(self, image='placeholder.png'):
1297 addons_path = http.addons_manifest['web']['addons_path']
1298 return open(os.path.join(addons_path, 'web', 'static', 'src', 'img', image), 'rb').read()
1300 @http.route('/web/binary/saveas', type='http', auth="user")
1301 @serialize_exception
1302 def saveas(self, model, field, id=None, filename_field=None, **kw):
1303 """ Download link for files stored as binary fields.
1305 If the ``id`` parameter is omitted, fetches the default value for the
1306 binary field (via ``default_get``), otherwise fetches the field for
1307 that precise record.
1309 :param str model: name of the model to fetch the binary from
1310 :param str field: binary field
1311 :param str id: id of the record from which to fetch the binary
1312 :param str filename_field: field holding the file's name, if any
1313 :returns: :class:`werkzeug.wrappers.Response`
1315 Model = request.session.model(model)
1318 fields.append(filename_field)
1320 res = Model.read([int(id)], fields, request.context)[0]
1322 res = Model.default_get(fields, request.context)
1323 filecontent = base64.b64decode(res.get(field, ''))
1325 return request.not_found()
1327 filename = '%s_%s' % (model.replace('.', '_'), id)
1329 filename = res.get(filename_field, '') or filename
1330 return request.make_response(filecontent,
1331 [('Content-Type', 'application/octet-stream'),
1332 ('Content-Disposition', content_disposition(filename))])
1334 @http.route('/web/binary/saveas_ajax', type='http', auth="user")
1335 @serialize_exception
1336 def saveas_ajax(self, data, token):
1337 jdata = simplejson.loads(data)
1338 model = jdata['model']
1339 field = jdata['field']
1340 data = jdata['data']
1341 id = jdata.get('id', None)
1342 filename_field = jdata.get('filename_field', None)
1343 context = jdata.get('context', {})
1345 Model = request.session.model(model)
1348 fields.append(filename_field)
1350 res = { field: data }
1352 res = Model.read([int(id)], fields, context)[0]
1354 res = Model.default_get(fields, context)
1355 filecontent = base64.b64decode(res.get(field, ''))
1357 raise ValueError(_("No content found for field '%s' on '%s:%s'") %
1360 filename = '%s_%s' % (model.replace('.', '_'), id)
1362 filename = res.get(filename_field, '') or filename
1363 return request.make_response(filecontent,
1364 headers=[('Content-Type', 'application/octet-stream'),
1365 ('Content-Disposition', content_disposition(filename))],
1366 cookies={'fileToken': token})
1368 @http.route('/web/binary/upload', type='http', auth="user")
1369 @serialize_exception
1370 def upload(self, callback, ufile):
1371 # TODO: might be useful to have a configuration flag for max-length file uploads
1372 out = """<script language="javascript" type="text/javascript">
1373 var win = window.top.window;
1374 win.jQuery(win).trigger(%s, %s);
1378 args = [len(data), ufile.filename,
1379 ufile.content_type, base64.b64encode(data)]
1380 except Exception, e:
1381 args = [False, e.message]
1382 return out % (simplejson.dumps(callback), simplejson.dumps(args))
1384 @http.route('/web/binary/upload_attachment', type='http', auth="user")
1385 @serialize_exception
1386 def upload_attachment(self, callback, model, id, ufile):
1387 Model = request.session.model('ir.attachment')
1388 out = """<script language="javascript" type="text/javascript">
1389 var win = window.top.window;
1390 win.jQuery(win).trigger(%s, %s);
1393 attachment_id = Model.create({
1394 'name': ufile.filename,
1395 'datas': base64.encodestring(ufile.read()),
1396 'datas_fname': ufile.filename,
1401 'filename': ufile.filename,
1405 args = {'error': "Something horrible happened"}
1406 return out % (simplejson.dumps(callback), simplejson.dumps(args))
1408 @http.route('/web/binary/company_logo', type='http', auth="none")
1409 def company_logo(self, dbname=None):
1410 # TODO add etag, refactor to use /image code for etag
1412 if request.session.db:
1413 dbname = request.session.db
1414 uid = request.session.uid
1415 elif dbname is None:
1416 dbname = db_monodb()
1419 uid = openerp.SUPERUSER_ID
1422 image_data = self.placeholder('logo.png')
1425 # create an empty registry
1426 registry = openerp.modules.registry.Registry(dbname)
1427 with registry.cursor() as cr:
1428 cr.execute("""SELECT c.logo_web
1430 LEFT JOIN res_company c
1431 ON c.id = u.company_id
1436 image_data = str(row[0]).decode('base64')
1438 image_data = self.placeholder('nologo.png')
1440 image_data = self.placeholder('logo.png')
1443 ('Content-Type', 'image/png'),
1444 ('Content-Length', len(image_data)),
1446 return request.make_response(image_data, headers)
1448 class Action(http.Controller):
1450 @http.route('/web/action/load', type='json', auth="user")
1451 def load(self, action_id, do_not_eval=False):
1452 Actions = request.session.model('ir.actions.actions')
1455 action_id = int(action_id)
1458 module, xmlid = action_id.split('.', 1)
1459 model, action_id = request.session.model('ir.model.data').get_object_reference(module, xmlid)
1460 assert model.startswith('ir.actions.')
1462 action_id = 0 # force failed read
1464 base_action = Actions.read([action_id], ['type'], request.context)
1467 action_type = base_action[0]['type']
1468 if action_type == 'ir.actions.report.xml':
1469 ctx.update({'bin_size': True})
1470 ctx.update(request.context)
1471 action = request.session.model(action_type).read([action_id], False, ctx)
1473 value = clean_action(action[0])
1476 @http.route('/web/action/run', type='json', auth="user")
1477 def run(self, action_id):
1478 return_action = request.session.model('ir.actions.server').run(
1479 [action_id], request.context)
1481 return clean_action(return_action)
1485 class Export(http.Controller):
1487 @http.route('/web/export/formats', type='json', auth="user")
1489 """ Returns all valid export formats
1491 :returns: for each export format, a pair of identifier and printable name
1492 :rtype: [(str, str)]
1495 {'tag': 'csv', 'label': 'CSV'},
1496 {'tag': 'xls', 'label': 'Excel', 'error': None if xlwt else "XLWT required"},
1499 def fields_get(self, model):
1500 Model = request.session.model(model)
1501 fields = Model.fields_get(False, request.context)
1504 @http.route('/web/export/get_fields', type='json', auth="user")
1505 def get_fields(self, model, prefix='', parent_name= '',
1506 import_compat=True, parent_field_type=None,
1509 if import_compat and parent_field_type == "many2one":
1512 fields = self.fields_get(model)
1515 fields.pop('id', None)
1517 fields['.id'] = fields.pop('id', {'string': 'ID'})
1519 fields_sequence = sorted(fields.iteritems(),
1520 key=lambda field: field[1].get('string', ''))
1523 for field_name, field in fields_sequence:
1525 if exclude and field_name in exclude:
1527 if field.get('readonly'):
1528 # If none of the field's states unsets readonly, skip the field
1529 if all(dict(attrs).get('readonly', True)
1530 for attrs in field.get('states', {}).values()):
1532 if not field.get('exportable', True):
1535 id = prefix + (prefix and '/'or '') + field_name
1536 name = parent_name + (parent_name and '/' or '') + field['string']
1537 record = {'id': id, 'string': name,
1538 'value': id, 'children': False,
1539 'field_type': field.get('type'),
1540 'required': field.get('required'),
1541 'relation_field': field.get('relation_field')}
1542 records.append(record)
1544 if len(name.split('/')) < 3 and 'relation' in field:
1545 ref = field.pop('relation')
1546 record['value'] += '/id'
1547 record['params'] = {'model': ref, 'prefix': id, 'name': name}
1549 if not import_compat or field['type'] == 'one2many':
1550 # m2m field in import_compat is childless
1551 record['children'] = True
1555 @http.route('/web/export/namelist', type='json', auth="user")
1556 def namelist(self, model, export_id):
1557 # TODO: namelist really has no reason to be in Python (although itertools.groupby helps)
1558 export = request.session.model("ir.exports").read([export_id])[0]
1559 export_fields_list = request.session.model("ir.exports.line").read(
1560 export['export_fields'])
1562 fields_data = self.fields_info(
1563 model, map(operator.itemgetter('name'), export_fields_list))
1566 {'name': field['name'], 'label': fields_data[field['name']]}
1567 for field in export_fields_list
1570 def fields_info(self, model, export_fields):
1572 fields = self.fields_get(model)
1573 if ".id" in export_fields:
1574 fields['.id'] = fields.pop('id', {'string': 'ID'})
1576 # To make fields retrieval more efficient, fetch all sub-fields of a
1577 # given field at the same time. Because the order in the export list is
1578 # arbitrary, this requires ordering all sub-fields of a given field
1579 # together so they can be fetched at the same time
1581 # Works the following way:
1582 # * sort the list of fields to export, the default sorting order will
1583 # put the field itself (if present, for xmlid) and all of its
1584 # sub-fields right after it
1585 # * then, group on: the first field of the path (which is the same for
1586 # a field and for its subfields and the length of splitting on the
1587 # first '/', which basically means grouping the field on one side and
1588 # all of the subfields on the other. This way, we have the field (for
1589 # the xmlid) with length 1, and all of the subfields with the same
1590 # base but a length "flag" of 2
1591 # * if we have a normal field (length 1), just add it to the info
1592 # mapping (with its string) as-is
1593 # * otherwise, recursively call fields_info via graft_subfields.
1594 # all graft_subfields does is take the result of fields_info (on the
1595 # field's model) and prepend the current base (current field), which
1596 # rebuilds the whole sub-tree for the field
1598 # result: because we're not fetching the fields_get for half the
1599 # database models, fetching a namelist with a dozen fields (including
1600 # relational data) falls from ~6s to ~300ms (on the leads model).
1601 # export lists with no sub-fields (e.g. import_compatible lists with
1602 # no o2m) are even more efficient (from the same 6s to ~170ms, as
1603 # there's a single fields_get to execute)
1604 for (base, length), subfields in itertools.groupby(
1605 sorted(export_fields),
1606 lambda field: (field.split('/', 1)[0], len(field.split('/', 1)))):
1607 subfields = list(subfields)
1609 # subfields is a seq of $base/*rest, and not loaded yet
1610 info.update(self.graft_subfields(
1611 fields[base]['relation'], base, fields[base]['string'],
1615 info[base] = fields[base]['string']
1619 def graft_subfields(self, model, prefix, prefix_string, fields):
1620 export_fields = [field.split('/', 1)[1] for field in fields]
1622 (prefix + '/' + k, prefix_string + '/' + v)
1623 for k, v in self.fields_info(model, export_fields).iteritems())
1625 class ExportFormat(object):
1627 def content_type(self):
1628 """ Provides the format's content type """
1629 raise NotImplementedError()
1631 def filename(self, base):
1632 """ Creates a valid filename for the format (with extension) from the
1633 provided base name (exension-less)
1635 raise NotImplementedError()
1637 def from_data(self, fields, rows):
1638 """ Conversion method from OpenERP's export data to whatever the
1639 current export class outputs
1641 :params list fields: a list of fields to export
1642 :params list rows: a list of records to export
1646 raise NotImplementedError()
1648 def base(self, data, token):
1649 model, fields, ids, domain, import_compat = \
1650 operator.itemgetter('model', 'fields', 'ids', 'domain',
1652 simplejson.loads(data))
1654 Model = request.session.model(model)
1655 ids = ids or Model.search(domain, 0, False, False, request.context)
1657 field_names = map(operator.itemgetter('name'), fields)
1658 import_data = Model.export_data(ids, field_names, request.context).get('datas',[])
1661 columns_headers = field_names
1663 columns_headers = [val['label'].strip() for val in fields]
1666 return request.make_response(self.from_data(columns_headers, import_data),
1667 headers=[('Content-Disposition',
1668 content_disposition(self.filename(model))),
1669 ('Content-Type', self.content_type)],
1670 cookies={'fileToken': token})
1672 class CSVExport(ExportFormat, http.Controller):
1674 @http.route('/web/export/csv', type='http', auth="user")
1675 @serialize_exception
1676 def index(self, data, token):
1677 return self.base(data, token)
1680 def content_type(self):
1681 return 'text/csv;charset=utf8'
1683 def filename(self, base):
1684 return base + '.csv'
1686 def from_data(self, fields, rows):
1688 writer = csv.writer(fp, quoting=csv.QUOTE_ALL)
1690 writer.writerow([name.encode('utf-8') for name in fields])
1695 if isinstance(d, basestring):
1696 d = d.replace('\n',' ').replace('\t',' ')
1698 d = d.encode('utf-8')
1699 except UnicodeError:
1701 if d is False: d = None
1703 writer.writerow(row)
1710 class ExcelExport(ExportFormat, http.Controller):
1712 @http.route('/web/export/xls', type='http', auth="user")
1713 @serialize_exception
1714 def index(self, data, token):
1715 return self.base(data, token)
1718 def content_type(self):
1719 return 'application/vnd.ms-excel'
1721 def filename(self, base):
1722 return base + '.xls'
1724 def from_data(self, fields, rows):
1725 workbook = xlwt.Workbook()
1726 worksheet = workbook.add_sheet('Sheet 1')
1728 for i, fieldname in enumerate(fields):
1729 worksheet.write(0, i, fieldname)
1730 worksheet.col(i).width = 8000 # around 220 pixels
1732 style = xlwt.easyxf('align: wrap yes')
1734 for row_index, row in enumerate(rows):
1735 for cell_index, cell_value in enumerate(row):
1736 if isinstance(cell_value, basestring):
1737 cell_value = re.sub("\r", " ", cell_value)
1738 if cell_value is False: cell_value = None
1739 worksheet.write(row_index + 1, cell_index, cell_value, style)
1748 class Reports(http.Controller):
1749 POLLING_DELAY = 0.25
1751 'doc': 'application/vnd.ms-word',
1752 'html': 'text/html',
1753 'odt': 'application/vnd.oasis.opendocument.text',
1754 'pdf': 'application/pdf',
1755 'sxw': 'application/vnd.sun.xml.writer',
1756 'xls': 'application/vnd.ms-excel',
1759 @http.route('/web/report', type='http', auth="user")
1760 @serialize_exception
1761 def index(self, action, token):
1762 action = simplejson.loads(action)
1764 report_srv = request.session.proxy("report")
1765 context = dict(request.context)
1766 context.update(action["context"])
1769 report_ids = context.get("active_ids", None)
1770 if 'report_type' in action:
1771 report_data['report_type'] = action['report_type']
1772 if 'datas' in action:
1773 if 'ids' in action['datas']:
1774 report_ids = action['datas'].pop('ids')
1775 report_data.update(action['datas'])
1777 report_id = report_srv.report(
1778 request.session.db, request.session.uid, request.session.password,
1779 action["report_name"], report_ids,
1780 report_data, context)
1782 report_struct = None
1784 report_struct = report_srv.report_get(
1785 request.session.db, request.session.uid, request.session.password, report_id)
1786 if report_struct["state"]:
1789 time.sleep(self.POLLING_DELAY)
1791 report = base64.b64decode(report_struct['result'])
1792 if report_struct.get('code') == 'zlib':
1793 report = zlib.decompress(report)
1794 report_mimetype = self.TYPES_MAPPING.get(
1795 report_struct['format'], 'octet-stream')
1796 file_name = action.get('name', 'report')
1797 if 'name' not in action:
1798 reports = request.session.model('ir.actions.report.xml')
1799 res_id = reports.search([('report_name', '=', action['report_name']),],
1800 0, False, False, context)
1802 file_name = reports.read(res_id[0], ['name'], context)['name']
1804 file_name = action['report_name']
1805 file_name = '%s.%s' % (file_name, report_struct['format'])
1807 return request.make_response(report,
1809 ('Content-Disposition', content_disposition(file_name)),
1810 ('Content-Type', report_mimetype),
1811 ('Content-Length', len(report))],
1812 cookies={'fileToken': token})
1814 # vim:expandtab:tabstop=4:softtabstop=4:shiftwidth=4: