You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

188 lines
6.8 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Adapted by Nicolas Bessi. Copyright Camptocamp SA
  5. # Based on Florent Xicluna original code. Copyright Wingo SA
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. import os
  22. import ConfigParser
  23. from lxml import etree
  24. from osv import osv, fields
  25. from tools.config import config as system_base_config
  26. from .system_info import get_server_environment
  27. import server_environment_files
  28. _dir = os.path.dirname(server_environment_files.__file__)
  29. # Same dict as RawConfigParser._boolean_states
  30. _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
  31. '0': False, 'no': False, 'false': False, 'off': False}
  32. if not system_base_config.get('running_env', False):
  33. raise Exception(
  34. ("The parameter 'running_env' has not be set neither in base config file option -c or in openerprc.\n"
  35. "We strongly recommand you not to use the rc file but instead use an explicite config file with this content : \n"
  36. "[options] \nrunning_env = dev")
  37. )
  38. ck_path = os.path.join(_dir, system_base_config['running_env'])
  39. if not os.path.exists(ck_path) :
  40. raise Exception(
  41. "Provided server environment does not exists please add a folder %s"%(ck_path)
  42. )
  43. def setboolean(obj, attr, _bool=_boolean_states):
  44. """Replace the attribute with a boolean."""
  45. res = _bool[getattr(obj, attr).lower()]
  46. setattr(obj, attr, res)
  47. return res
  48. # Borrowed from MarkupSafe
  49. def _escape(s):
  50. """Convert the characters &<>'" in string s to HTML-safe sequences."""
  51. return (str(s).replace('&', '&amp;')
  52. .replace('>', '&gt;')
  53. .replace('<', '&lt;')
  54. .replace("'", '&#39;')
  55. .replace('"', '&#34;'))
  56. def _listconf(env_path):
  57. """List configuration files in a folder."""
  58. files = [os.path.join(env_path, name)
  59. for name in sorted(os.listdir(env_path))
  60. if name.endswith('.conf')]
  61. return files
  62. def _load_config():
  63. """Load the configuration and return a ConfigParser instance."""
  64. default = os.path.join(_dir, 'default')
  65. running_env = os.path.join(_dir, system_base_config['running_env'])
  66. if os.path.isdir(default):
  67. conf_files = _listconf(default) + _listconf(running_env)
  68. else:
  69. conf_files = _listconf(running_env)
  70. config_p = ConfigParser.SafeConfigParser()
  71. # options are case-sensitive
  72. config_p.optionxform = str
  73. try:
  74. config_p.read(conf_files)
  75. except Exception, e:
  76. raise Exception('Cannot read config files "%s": %s' % (conf_files, e))
  77. return config_p
  78. serv_config = _load_config()
  79. class _Defaults(dict):
  80. __slots__ = ()
  81. def __setitem__(self, key, value):
  82. func = lambda *a: str(value)
  83. return dict.__setitem__(self, key, func)
  84. class ServerConfiguration(osv.osv_memory):
  85. """Display server configuration."""
  86. _name = 'server.config'
  87. _columns = {}
  88. _conf_defaults = _Defaults()
  89. def __init__(self, pool, cr):
  90. res = super(ServerConfiguration, self).__init__(pool, cr)
  91. self.running_env = system_base_config['running_env']
  92. # Only show passwords in development
  93. self.show_passwords = self.running_env in ('dev',)
  94. self._build_osv()
  95. return res
  96. def _group(self, items, prefix):
  97. """Return an XML chunk which represents a group of fields."""
  98. names = []
  99. for k, v in items:
  100. key = '%s\\%s' % (prefix, k)
  101. # Mask passwords
  102. if 'passw' in k and not self.show_passwords:
  103. v = '**********'
  104. # for the GTK display, we need to replace '_' with '__'.
  105. # XXX: remove this hack when we switch to the web client.
  106. k = k.replace('_', '__')
  107. self._columns[key] = fields.char(k, size=1024)
  108. self._conf_defaults[key] = v
  109. names.append(key)
  110. return ('<group col="2" colspan="4">' +
  111. ''.join(['<field name="%s" readonly="1"/>' %
  112. _escape(name) for name in names]) +
  113. '</group>')
  114. def _build_osv(self):
  115. """Build the view for the current configuration."""
  116. arch = ('<?xml version="1.0" encoding="utf-8"?>'
  117. '<form string="Configuration Form">'
  118. '<notebook colspan="4">')
  119. # OpenERP server configuration
  120. rcfile = system_base_config.rcfile
  121. items = sorted(system_base_config.options.items())
  122. arch += '<page string="OpenERP">'
  123. arch += '<separator string="%s" colspan="4"/>' % _escape(rcfile)
  124. arch += self._group(items, prefix='openerp')
  125. arch += '<separator colspan="4"/></page>'
  126. arch += '<page string="Environment based configurations">'
  127. for section in sorted(serv_config.sections()):
  128. items = sorted(serv_config.items(section))
  129. arch += '<separator string="[%s]" colspan="4"/>' % _escape(section)
  130. arch += self._group(items, prefix=section)
  131. arch += '<separator colspan="4"/></page>'
  132. # System information
  133. arch += '<page string="System">'
  134. arch += '<separator string="Server Environment" colspan="4"/>'
  135. arch += self._group(get_server_environment(), prefix='system')
  136. arch += '<separator colspan="4"/></page>'
  137. arch += '</notebook></form>'
  138. self._arch = etree.fromstring(arch)
  139. def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
  140. """Overwrite the default method to render the custom view."""
  141. res = super(ServerConfiguration, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar)
  142. if view_type == 'form':
  143. arch_node = self._arch
  144. xarch, xfields = self._view_look_dom_arch(cr, uid, arch_node, view_id, context=context)
  145. res['arch'] = xarch
  146. res['fields'] = xfields
  147. return res
  148. def default_get(self, cr, uid, fields_list, context=None):
  149. res = {}
  150. for key in self._conf_defaults:
  151. res[key] = self._conf_defaults[key]()
  152. return res
  153. ServerConfiguration()