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.

195 lines
7.1 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 openerp.osv import osv, fields, orm
  25. from openerp.tools.config import config as system_base_config
  26. from .system_info import get_server_environment
  27. from openerp.addons 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 "
  35. "file option -c or in openerprc.\n"
  36. "We strongly recommend against using the rc file but instead use an "
  37. "explicit config file with this content:\n"
  38. "[options]\nrunning_env = dev"
  39. )
  40. ck_path = os.path.join(_dir, system_base_config['running_env'])
  41. if not os.path.exists(ck_path) :
  42. raise Exception(
  43. "Provided server environment does not exist, "
  44. "please add a folder %s" % ck_path
  45. )
  46. def setboolean(obj, attr, _bool=_boolean_states):
  47. """Replace the attribute with a boolean."""
  48. res = _bool[getattr(obj, attr).lower()]
  49. setattr(obj, attr, res)
  50. return res
  51. # Borrowed from MarkupSafe
  52. def _escape(s):
  53. """Convert the characters &<>'" in string s to HTML-safe sequences."""
  54. return (str(s).replace('&', '&amp;')
  55. .replace('>', '&gt;')
  56. .replace('<', '&lt;')
  57. .replace("'", '&#39;')
  58. .replace('"', '&#34;'))
  59. def _listconf(env_path):
  60. """List configuration files in a folder."""
  61. files = [os.path.join(env_path, name)
  62. for name in sorted(os.listdir(env_path))
  63. if name.endswith('.conf')]
  64. return files
  65. def _load_config():
  66. """Load the configuration and return a ConfigParser instance."""
  67. default = os.path.join(_dir, 'default')
  68. running_env = os.path.join(_dir,
  69. system_base_config['running_env'])
  70. if os.path.isdir(default):
  71. conf_files = _listconf(default) + _listconf(running_env)
  72. else:
  73. conf_files = _listconf(running_env)
  74. config_p = ConfigParser.SafeConfigParser()
  75. # options are case-sensitive
  76. config_p.optionxform = str
  77. try:
  78. config_p.read(conf_files)
  79. except Exception, e:
  80. raise Exception('Cannot read config files "%s": %s' % (conf_files, e))
  81. return config_p
  82. serv_config = _load_config()
  83. class _Defaults(dict):
  84. __slots__ = ()
  85. def __setitem__(self, key, value):
  86. func = lambda *a: str(value)
  87. return dict.__setitem__(self, key, func)
  88. class ServerConfiguration(orm.TransientModel):
  89. """Display server configuration."""
  90. _name = 'server.config'
  91. _columns = {}
  92. _conf_defaults = _Defaults()
  93. def __init__(self, pool, cr):
  94. res = super(ServerConfiguration, self).__init__(pool, cr)
  95. self.running_env = system_base_config['running_env']
  96. # Only show passwords in development
  97. self.show_passwords = self.running_env in ('dev',)
  98. self._arch = None
  99. self._build_osv()
  100. def _group(self, items, prefix):
  101. """Return an XML chunk which represents a group of fields."""
  102. names = []
  103. for k, v in items:
  104. key = '%s\\%s' % (prefix, k)
  105. # Mask passwords
  106. if 'passw' in k and not self.show_passwords:
  107. v = '**********'
  108. self._columns[key] = fields.char(k, size=1024)
  109. self._conf_defaults[key] = v
  110. names.append(key)
  111. return ('<group col="2" colspan="4">' +
  112. ''.join(['<field name="%s" readonly="1"/>' %
  113. _escape(name) for name in names]) +
  114. '</group>')
  115. def _build_osv(self):
  116. """Build the view for the current configuration."""
  117. arch = ('<?xml version="1.0" encoding="utf-8"?>'
  118. '<form string="Configuration Form">'
  119. '<notebook colspan="4">')
  120. # OpenERP server configuration
  121. rcfile = system_base_config.rcfile
  122. items = sorted(system_base_config.options.items())
  123. arch += '<page string="OpenERP">'
  124. arch += '<separator string="%s" colspan="4"/>' % _escape(rcfile)
  125. arch += self._group(items, prefix='openerp')
  126. arch += '<separator colspan="4"/></page>'
  127. arch += '<page string="Environment based configurations">'
  128. for section in sorted(serv_config.sections()):
  129. items = sorted(serv_config.items(section))
  130. arch += '<separator string="[%s]" colspan="4"/>' % _escape(section)
  131. arch += self._group(items, prefix=section)
  132. arch += '<separator colspan="4"/></page>'
  133. # System information
  134. arch += '<page string="System">'
  135. arch += '<separator string="Server Environment" colspan="4"/>'
  136. arch += self._group(get_server_environment(), prefix='system')
  137. arch += '<separator colspan="4"/></page>'
  138. arch += '</notebook></form>'
  139. self._arch = etree.fromstring(arch)
  140. def fields_view_get(self, cr, uid, view_id=None, view_type='form',
  141. context=None, toolbar=False, submenu=False):
  142. """Overwrite the default method to render the custom view."""
  143. res = super(ServerConfiguration, self).fields_view_get(cr, uid,
  144. view_id,
  145. view_type,
  146. context,
  147. toolbar)
  148. if view_type == 'form':
  149. arch_node = self._arch
  150. xarch, xfields = self._view_look_dom_arch(cr, uid,
  151. arch_node,
  152. view_id,
  153. context=context)
  154. res['arch'] = xarch
  155. res['fields'] = xfields
  156. return res
  157. def default_get(self, cr, uid, fields_list, context=None):
  158. res = {}
  159. for key in self._conf_defaults:
  160. res[key] = self._conf_defaults[key]()
  161. return res