[IMP] Improved the Search View.
[odoo/odoo.git] / openerp / addons / base / module / module.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2012 OpenERP S.A. (<http://openerp.com>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (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 Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21 import imp
22 import logging
23 import re
24 import urllib
25 import zipimport
26
27 from openerp import modules, pooler, release, tools
28 from openerp.tools.parse_version import parse_version
29 from openerp.tools.translate import _
30 from openerp.osv import fields, osv, orm
31
32 _logger = logging.getLogger(__name__)
33
34 ACTION_DICT = {
35     'view_type': 'form',
36     'view_mode': 'form',
37     'res_model': 'base.module.upgrade',
38     'target': 'new',
39     'type': 'ir.actions.act_window',
40     'nodestroy':True,
41 }
42
43 class module_category(osv.osv):
44     _name = "ir.module.category"
45     _description = "Application"
46
47     def _module_nbr(self,cr,uid, ids, prop, unknow_none, context):
48         cr.execute('SELECT category_id, COUNT(*) \
49                       FROM ir_module_module \
50                      WHERE category_id IN %(ids)s \
51                         OR category_id IN (SELECT id \
52                                              FROM ir_module_category \
53                                             WHERE parent_id IN %(ids)s) \
54                      GROUP BY category_id', {'ids': tuple(ids)}
55                     )
56         result = dict(cr.fetchall())
57         for id in ids:
58             cr.execute('select id from ir_module_category where parent_id=%s', (id,))
59             result[id] = sum([result.get(c, 0) for (c,) in cr.fetchall()],
60                              result.get(id, 0))
61         return result
62
63     _columns = {
64         'name': fields.char("Name", size=128, required=True, translate=True, select=True),
65         'parent_id': fields.many2one('ir.module.category', 'Parent Application', select=True),
66         'child_ids': fields.one2many('ir.module.category', 'parent_id', 'Child Applications'),
67         'module_nr': fields.function(_module_nbr, string='Number of Modules', type='integer'),
68         'module_ids' : fields.one2many('ir.module.module', 'category_id', 'Modules'),
69         'description' : fields.text("Description", translate=True),
70         'sequence' : fields.integer('Sequence'),
71         'visible' : fields.boolean('Visible'),
72         'xml_id': fields.function(osv.osv.get_external_id, type='char', size=128, string="External ID"),
73     }
74     _order = 'name'
75
76     _defaults = {
77         'visible' : 1,
78     }
79
80 class module(osv.osv):
81     _name = "ir.module.module"
82     _description = "Module"
83
84     @classmethod
85     def get_module_info(cls, name):
86         info = {}
87         try:
88             info = modules.load_information_from_description_file(name)
89             info['version'] = release.major_version + '.' + info['version']
90         except Exception:
91             _logger.debug('Error when trying to fetch informations for '
92                           'module %s', name, exc_info=True)
93         return info
94
95     def _get_latest_version(self, cr, uid, ids, field_name=None, arg=None, context=None):
96         res = dict.fromkeys(ids, '')
97         for m in self.browse(cr, uid, ids):
98             res[m.id] = self.get_module_info(m.name).get('version', '')
99         return res
100
101     def _get_views(self, cr, uid, ids, field_name=None, arg=None, context=None):
102         res = {}
103         model_data_obj = self.pool.get('ir.model.data')
104         view_obj = self.pool.get('ir.ui.view')
105         report_obj = self.pool.get('ir.actions.report.xml')
106         menu_obj = self.pool.get('ir.ui.menu')
107
108         dmodels = []
109         if field_name is None or 'views_by_module' in field_name:
110             dmodels.append('ir.ui.view')
111         if field_name is None or 'reports_by_module' in field_name:
112             dmodels.append('ir.actions.report.xml')
113         if field_name is None or 'menus_by_module' in field_name:
114             dmodels.append('ir.ui.menu')
115         assert dmodels, "no models for %s" % field_name
116
117         for module_rec in self.browse(cr, uid, ids, context=context):
118             res[module_rec.id] = {
119                 'menus_by_module': [],
120                 'reports_by_module': [],
121                 'views_by_module': []
122             }
123
124             # Skip uninstalled modules below, no data to find anyway.
125             if module_rec.state not in ('installed', 'to upgrade', 'to remove'):
126                 continue
127
128             # then, search and group ir.model.data records
129             imd_models = dict( [(m,[]) for m in dmodels])
130             imd_ids = model_data_obj.search(cr,uid,[('module','=', module_rec.name),
131                 ('model','in',tuple(dmodels))])
132
133             for imd_res in model_data_obj.read(cr, uid, imd_ids, ['model', 'res_id'], context=context):
134                 imd_models[imd_res['model']].append(imd_res['res_id'])
135
136             # For each one of the models, get the names of these ids.
137             # We use try except, because views or menus may not exist.
138             try:
139                 res_mod_dic = res[module_rec.id]
140                 for v in view_obj.browse(cr, uid, imd_models.get('ir.ui.view', []), context=context):
141                     aa = v.inherit_id and '* INHERIT ' or ''
142                     res_mod_dic['views_by_module'].append(aa + v.name + '('+v.type+')')
143
144                 for rx in report_obj.browse(cr, uid, imd_models.get('ir.actions.report.xml', []), context=context):
145                     res_mod_dic['reports_by_module'].append(rx.name)
146
147                 for um in menu_obj.browse(cr, uid, imd_models.get('ir.ui.menu', []), context=context):
148                     res_mod_dic['menus_by_module'].append(um.complete_name)
149             except KeyError, e:
150                 _logger.warning(
151                       'Data not found for items of %s', module_rec.name)
152             except AttributeError, e:
153                 _logger.warning(
154                       'Data not found for items of %s %s', module_rec.name, str(e))
155             except Exception, e:
156                 _logger.warning('Unknown error while fetching data of %s',
157                       module_rec.name, exc_info=True)
158         for key, _ in res.iteritems():
159             for k, v in res[key].iteritems():
160                 res[key][k] = "\n".join(sorted(v))
161         return res
162
163     _columns = {
164         'name': fields.char("Technical Name", size=128, readonly=True, required=True, select=True),
165         'category_id': fields.many2one('ir.module.category', 'Category', readonly=True, select=True),
166         'shortdesc': fields.char('Module Name', size=256, readonly=True, translate=True),
167         'description': fields.text("Description", readonly=True, translate=True),
168         'author': fields.char("Author", size=128, readonly=True),
169         'maintainer': fields.char('Maintainer', size=128, readonly=True),
170         'contributors': fields.text('Contributors', readonly=True),
171         'website': fields.char("Website", size=256, readonly=True),
172
173         # attention: Incorrect field names !!
174         #   installed_version refer the latest version (the one on disk)
175         #   latest_version refer the installed version (the one in database)
176         #   published_version refer the version available on the repository
177         'installed_version': fields.function(_get_latest_version,
178             string='Latest Version', type='char'),
179         'latest_version': fields.char('Installed Version', size=64, readonly=True),
180         'published_version': fields.char('Published Version', size=64, readonly=True),
181
182         'url': fields.char('URL', size=128, readonly=True),
183         'sequence': fields.integer('Sequence'),
184         'dependencies_id': fields.one2many('ir.module.module.dependency',
185             'module_id', 'Dependencies', readonly=True),
186         'auto_install': fields.boolean('Automatic Installation',
187             help='An auto-installable module is automatically installed by the '
188             'system when all its dependencies are satisfied. '
189             'If the module has no dependency, it is always installed.'),
190         'state': fields.selection([
191             ('uninstallable','Not Installable'),
192             ('uninstalled','Not Installed'),
193             ('installed','Installed'),
194             ('to upgrade','To be upgraded'),
195             ('to remove','To be removed'),
196             ('to install','To be installed')
197         ], string='State', readonly=True, select=True),
198         'demo': fields.boolean('Demo Data', readonly=True),
199         'license': fields.selection([
200                 ('GPL-2', 'GPL Version 2'),
201                 ('GPL-2 or any later version', 'GPL-2 or later version'),
202                 ('GPL-3', 'GPL Version 3'),
203                 ('GPL-3 or any later version', 'GPL-3 or later version'),
204                 ('AGPL-3', 'Affero GPL-3'),
205                 ('Other OSI approved licence', 'Other OSI Approved Licence'),
206                 ('Other proprietary', 'Other Proprietary')
207             ], string='License', readonly=True),
208         'menus_by_module': fields.function(_get_views, string='Menus', type='text', multi="meta", store=True),
209         'reports_by_module': fields.function(_get_views, string='Reports', type='text', multi="meta", store=True),
210         'views_by_module': fields.function(_get_views, string='Views', type='text', multi="meta", store=True),
211         'certificate' : fields.char('Quality Certificate', size=64, readonly=True),
212         'application': fields.boolean('Application', readonly=True),
213         'icon': fields.char('Icon URL', size=128),
214     }
215
216     _defaults = {
217         'state': 'uninstalled',
218         'sequence': 100,
219         'demo': False,
220         'license': 'AGPL-3',
221     }
222     _order = 'sequence,name'
223
224     def _name_uniq_msg(self, cr, uid, ids, context=None):
225         return _('The name of the module must be unique !')
226     def _certificate_uniq_msg(self, cr, uid, ids, context=None):
227         return _('The certificate ID of the module must be unique !')
228
229     _sql_constraints = [
230         ('name_uniq', 'UNIQUE (name)',_name_uniq_msg ),
231         ('certificate_uniq', 'UNIQUE (certificate)',_certificate_uniq_msg )
232     ]
233
234     def unlink(self, cr, uid, ids, context=None):
235         if not ids:
236             return True
237         if isinstance(ids, (int, long)):
238             ids = [ids]
239         mod_names = []
240         for mod in self.read(cr, uid, ids, ['state','name'], context):
241             if mod['state'] in ('installed', 'to upgrade', 'to remove', 'to install'):
242                 raise orm.except_orm(_('Error'),
243                         _('You try to remove a module that is installed or will be installed'))
244             mod_names.append(mod['name'])
245         #Removing the entry from ir_model_data
246         #ids_meta = self.pool.get('ir.model.data').search(cr, uid, [('name', '=', 'module_meta_information'), ('module', 'in', mod_names)])
247
248         #if ids_meta:
249         #    self.pool.get('ir.model.data').unlink(cr, uid, ids_meta, context)
250
251         return super(module, self).unlink(cr, uid, ids, context=context)
252
253     @staticmethod
254     def _check_external_dependencies(terp):
255         depends = terp.get('external_dependencies')
256         if not depends:
257             return
258         for pydep in depends.get('python', []):
259             parts = pydep.split('.')
260             parts.reverse()
261             path = None
262             while parts:
263                 part = parts.pop()
264                 try:
265                     _, path, _ = imp.find_module(part, path and [path] or None)
266                 except ImportError:
267                     raise ImportError('No module named %s' % (pydep,))
268
269         for binary in depends.get('bin', []):
270             if tools.find_in_path(binary) is None:
271                 raise Exception('Unable to find %r in path' % (binary,))
272
273     @classmethod
274     def check_external_dependencies(cls, module_name, newstate='to install'):
275         terp = cls.get_module_info(module_name)
276         try:
277             cls._check_external_dependencies(terp)
278         except Exception, e:
279             if newstate == 'to install':
280                 msg = _('Unable to install module "%s" because an external dependency is not met: %s')
281             elif newstate == 'to upgrade':
282                 msg = _('Unable to upgrade module "%s" because an external dependency is not met: %s')
283             else:
284                 msg = _('Unable to process module "%s" because an external dependency is not met: %s')
285             raise orm.except_orm(_('Error'), msg % (module_name, e.args[0]))
286
287     def state_update(self, cr, uid, ids, newstate, states_to_update, context=None, level=100):
288         if level<1:
289             raise orm.except_orm(_('Error'), _('Recursion error in modules dependencies !'))
290         demo = False
291         for module in self.browse(cr, uid, ids, context=context):
292             mdemo = False
293             for dep in module.dependencies_id:
294                 if dep.state == 'unknown':
295                     raise orm.except_orm(_('Error'), _("You try to install module '%s' that depends on module '%s'.\nBut the latter module is not available in your system.") % (module.name, dep.name,))
296                 ids2 = self.search(cr, uid, [('name','=',dep.name)])
297                 if dep.state != newstate:
298                     mdemo = self.state_update(cr, uid, ids2, newstate, states_to_update, context, level-1,) or mdemo
299                 else:
300                     od = self.browse(cr, uid, ids2)[0]
301                     mdemo = od.demo or mdemo
302
303             self.check_external_dependencies(module.name, newstate)
304             if not module.dependencies_id:
305                 mdemo = module.demo
306             if module.state in states_to_update:
307                 self.write(cr, uid, [module.id], {'state': newstate, 'demo':mdemo})
308             demo = demo or mdemo
309         return demo
310
311     def button_install(self, cr, uid, ids, context=None):
312
313         # Mark the given modules to be installed.
314         self.state_update(cr, uid, ids, 'to install', ['uninstalled'], context)
315
316         # Mark (recursively) the newly satisfied modules to also be installed:
317
318         # Select all auto-installable (but not yet installed) modules.
319         domain = [('state', '=', 'uninstalled'), ('auto_install', '=', True),]
320         uninstalled_ids = self.search(cr, uid, domain, context=context)
321         uninstalled_modules = self.browse(cr, uid, uninstalled_ids, context=context)
322
323         # Keep those with all their dependencies satisfied.
324         def all_depencies_satisfied(m):
325             return all(x.state in ('to install', 'installed', 'to upgrade') for x in m.dependencies_id)
326         to_install_modules = filter(all_depencies_satisfied, uninstalled_modules)
327         to_install_ids = map(lambda m: m.id, to_install_modules)
328
329         # Mark them to be installed.
330         if to_install_ids:
331             self.button_install(cr, uid, to_install_ids, context=context)
332         return dict(ACTION_DICT, name=_('Install'))
333
334     def button_immediate_install(self, cr, uid, ids, context=None):
335         """ Installs the selected module(s) immediately and fully,
336         returns the next res.config action to execute
337
338         :param ids: identifiers of the modules to install
339         :returns: next res.config item to execute
340         :rtype: dict[str, object]
341         """
342         self.button_install(cr, uid, ids, context=context)
343         cr.commit()
344         _, pool = pooler.restart_pool(cr.dbname, update_module=True)
345
346         config = pool.get('res.config').next(cr, uid, [], context=context) or {}
347         if config.get('type') not in ('ir.actions.reload', 'ir.actions.act_window_close'):
348             return config
349
350         # reload the client
351         menu_ids = self.root_menus(cr,uid,ids,context)
352         return {
353             'type': 'ir.actions.client',
354             'tag': 'reload',
355             'params': {'menu_id': menu_ids and menu_ids[0] or False},
356         }
357
358     def button_install_cancel(self, cr, uid, ids, context=None):
359         self.write(cr, uid, ids, {'state': 'uninstalled', 'demo':False})
360         return True
361
362     def module_uninstall(self, cr, uid, ids, context=None):
363         """Perform the various steps required to uninstall a module completely
364         including the deletion of all database structures created by the module:
365         tables, columns, constraints, etc."""
366         ir_model_data = self.pool.get('ir.model.data')
367         modules_to_remove = [m.name for m in self.browse(cr, uid, ids, context)]
368         data_ids = ir_model_data.search(cr, uid, [('module', 'in', modules_to_remove)])
369         ir_model_data._module_data_uninstall(cr, uid, data_ids, context)
370         ir_model_data.unlink(cr, uid, data_ids, context)
371         self.write(cr, uid, ids, {'state': 'uninstalled'})
372         return True
373
374     def downstream_dependencies(self, cr, uid, ids, known_dep_ids=None,
375                                 exclude_states=['uninstalled','uninstallable','to remove'],
376                                 context=None):
377         """Return the ids of all modules that directly or indirectly depend
378         on the given module `ids`, and that satisfy the `exclude_states`
379         filter"""
380         if not ids: return []
381         known_dep_ids = set(known_dep_ids or [])
382         cr.execute('''SELECT DISTINCT m.id
383                         FROM
384                             ir_module_module_dependency d
385                         JOIN
386                             ir_module_module m ON (d.module_id=m.id)
387                         WHERE
388                             d.name IN (SELECT name from ir_module_module where id in %s) AND
389                             m.state NOT IN %s AND
390                             m.id NOT IN %s ''',
391                    (tuple(ids),tuple(exclude_states), tuple(known_dep_ids or ids)))
392         new_dep_ids = set([m[0] for m in cr.fetchall()])
393         missing_mod_ids = new_dep_ids - known_dep_ids
394         known_dep_ids |= new_dep_ids
395         if missing_mod_ids:
396             known_dep_ids |= set(self.downstream_dependencies(cr, uid, list(missing_mod_ids),
397                                                           known_dep_ids, exclude_states,context))
398         return list(known_dep_ids)
399
400     def button_uninstall(self, cr, uid, ids, context=None):
401         if any(m.name == 'base' for m in self.browse(cr, uid, ids)):
402             raise orm.except_orm(_('Error'), _("The `base` module cannot be uninstalled"))
403         dep_ids = self.downstream_dependencies(cr, uid, ids, context=context)
404         self.write(cr, uid, ids + dep_ids, {'state': 'to remove'})
405         return dict(ACTION_DICT, name=_('Uninstall'))
406
407     def button_uninstall_cancel(self, cr, uid, ids, context=None):
408         self.write(cr, uid, ids, {'state': 'installed'})
409         return True
410
411     def button_upgrade(self, cr, uid, ids, context=None):
412         depobj = self.pool.get('ir.module.module.dependency')
413         todo = self.browse(cr, uid, ids, context=context)
414         self.update_list(cr, uid)
415
416         i = 0
417         while i<len(todo):
418             mod = todo[i]
419             i += 1
420             if mod.state not in ('installed','to upgrade'):
421                 raise orm.except_orm(_('Error'),
422                         _("Can not upgrade module '%s'. It is not installed.") % (mod.name,))
423             self.check_external_dependencies(mod.name, 'to upgrade')
424             iids = depobj.search(cr, uid, [('name', '=', mod.name)], context=context)
425             for dep in depobj.browse(cr, uid, iids, context=context):
426                 if dep.module_id.state=='installed' and dep.module_id not in todo:
427                     todo.append(dep.module_id)
428
429         ids = map(lambda x: x.id, todo)
430         self.write(cr, uid, ids, {'state':'to upgrade'}, context=context)
431
432         to_install = []
433         for mod in todo:
434             for dep in mod.dependencies_id:
435                 if dep.state == 'unknown':
436                     raise orm.except_orm(_('Error'), _('You try to upgrade a module that depends on the module: %s.\nBut this module is not available in your system.') % (dep.name,))
437                 if dep.state == 'uninstalled':
438                     ids2 = self.search(cr, uid, [('name','=',dep.name)])
439                     to_install.extend(ids2)
440
441         self.button_install(cr, uid, to_install, context=context)
442         return dict(ACTION_DICT, name=_('Upgrade'))
443
444     def button_upgrade_cancel(self, cr, uid, ids, context=None):
445         self.write(cr, uid, ids, {'state': 'installed'})
446         return True
447
448     def button_update_translations(self, cr, uid, ids, context=None):
449         self.update_translations(cr, uid, ids)
450         return True
451
452     @staticmethod
453     def get_values_from_terp(terp):
454         return {
455             'description': terp.get('description', ''),
456             'shortdesc': terp.get('name', ''),
457             'author': terp.get('author', 'Unknown'),
458             'maintainer': terp.get('maintainer', False),
459             'contributors': ', '.join(terp.get('contributors', [])) or False,
460             'website': terp.get('website', ''),
461             'license': terp.get('license', 'AGPL-3'),
462             'certificate': terp.get('certificate') or False,
463             'sequence': terp.get('sequence', 100),
464             'application': terp.get('application', False),
465             'auto_install': terp.get('auto_install', False),
466             'icon': terp.get('icon', False),
467         }
468
469     # update the list of available packages
470     def update_list(self, cr, uid, context=None):
471         res = [0, 0] # [update, add]
472
473         known_mods = self.browse(cr, uid, self.search(cr, uid, []))
474         known_mods_names = dict([(m.name, m) for m in known_mods])
475
476         # iterate through detected modules and update/create them in db
477         for mod_name in modules.get_modules():
478             mod = known_mods_names.get(mod_name)
479             terp = self.get_module_info(mod_name)
480             values = self.get_values_from_terp(terp)
481
482             if mod:
483                 updated_values = {}
484                 for key in values:
485                     old = getattr(mod, key)
486                     updated = isinstance(values[key], basestring) and tools.ustr(values[key]) or values[key]
487                     if not old == updated:
488                         updated_values[key] = values[key]
489                 if terp.get('installable', True) and mod.state == 'uninstallable':
490                     updated_values['state'] = 'uninstalled'
491                 if parse_version(terp.get('version', '')) > parse_version(mod.latest_version or ''):
492                     res[0] += 1
493                 if updated_values:
494                     self.write(cr, uid, mod.id, updated_values)
495             else:
496                 mod_path = modules.get_module_path(mod_name)
497                 if not mod_path:
498                     continue
499                 if not terp or not terp.get('installable', True):
500                     continue
501                 id = self.create(cr, uid, dict(name=mod_name, state='uninstalled', **values))
502                 mod = self.browse(cr, uid, id)
503                 res[1] += 1
504
505             self._update_dependencies(cr, uid, mod, terp.get('depends', []))
506             self._update_category(cr, uid, mod, terp.get('category', 'Uncategorized'))
507
508         return res
509
510     def download(self, cr, uid, ids, download=True, context=None):
511         res = []
512         for mod in self.browse(cr, uid, ids, context=context):
513             if not mod.url:
514                 continue
515             match = re.search('-([a-zA-Z0-9\._-]+)(\.zip)', mod.url, re.I)
516             version = '0'
517             if match:
518                 version = match.group(1)
519             if parse_version(mod.installed_version or '0') >= parse_version(version):
520                 continue
521             res.append(mod.url)
522             if not download:
523                 continue
524             zip_content = urllib.urlopen(mod.url).read()
525             fname = modules.get_module_path(str(mod.name)+'.zip', downloaded=True)
526             try:
527                 with open(fname, 'wb') as fp:
528                     fp.write(zip_content)
529             except Exception:
530                 _logger.exception('Error when trying to create module '
531                                   'file %s', fname)
532                 raise orm.except_orm(_('Error'), _('Can not create the module file:\n %s') % (fname,))
533             terp = self.get_module_info(mod.name)
534             self.write(cr, uid, mod.id, self.get_values_from_terp(terp))
535             cr.execute('DELETE FROM ir_module_module_dependency ' \
536                     'WHERE module_id = %s', (mod.id,))
537             self._update_dependencies(cr, uid, mod, terp.get('depends',
538                 []))
539             self._update_category(cr, uid, mod, terp.get('category',
540                 'Uncategorized'))
541             # Import module
542             zimp = zipimport.zipimporter(fname)
543             zimp.load_module(mod.name)
544         return res
545
546     def _update_dependencies(self, cr, uid, mod_browse, depends=None):
547         if depends is None:
548             depends = []
549         existing = set(x.name for x in mod_browse.dependencies_id)
550         needed = set(depends)
551         for dep in (needed - existing):
552             cr.execute('INSERT INTO ir_module_module_dependency (module_id, name) values (%s, %s)', (mod_browse.id, dep))
553         for dep in (existing - needed):
554             cr.execute('DELETE FROM ir_module_module_dependency WHERE module_id = %s and name = %s', (mod_browse.id, dep))
555
556     def _update_category(self, cr, uid, mod_browse, category='Uncategorized'):
557         current_category = mod_browse.category_id
558         current_category_path = []
559         while current_category:
560             current_category_path.insert(0, current_category.name)
561             current_category = current_category.parent_id
562
563         categs = category.split('/')
564         if categs != current_category_path:
565             p_id = None
566             while categs:
567                 if p_id is not None:
568                     cr.execute('SELECT id FROM ir_module_category WHERE name=%s AND parent_id=%s', (categs[0], p_id))
569                 else:
570                     cr.execute('SELECT id FROM ir_module_category WHERE name=%s AND parent_id is NULL', (categs[0],))
571                 c_id = cr.fetchone()
572                 if not c_id:
573                     cr.execute('INSERT INTO ir_module_category (name, parent_id) VALUES (%s, %s) RETURNING id', (categs[0], p_id))
574                     c_id = cr.fetchone()[0]
575                 else:
576                     c_id = c_id[0]
577                 p_id = c_id
578                 categs = categs[1:]
579             self.write(cr, uid, [mod_browse.id], {'category_id': p_id})
580
581     def update_translations(self, cr, uid, ids, filter_lang=None, context=None):
582         if context is None:
583             context = {}
584         if not filter_lang:
585             pool = pooler.get_pool(cr.dbname)
586             lang_obj = pool.get('res.lang')
587             lang_ids = lang_obj.search(cr, uid, [('translatable', '=', True)])
588             filter_lang = [lang.code for lang in lang_obj.browse(cr, uid, lang_ids)]
589         elif not isinstance(filter_lang, (list, tuple)):
590             filter_lang = [filter_lang]
591
592         for mod in self.browse(cr, uid, ids):
593             if mod.state != 'installed':
594                 continue
595             modpath = modules.get_module_path(mod.name)
596             if not modpath:
597                 # unable to find the module. we skip
598                 continue
599             for lang in filter_lang:
600                 iso_lang = tools.get_iso_codes(lang)
601                 f = modules.get_module_resource(mod.name, 'i18n', iso_lang + '.po')
602                 context2 = context and context.copy() or {}
603                 if f and '_' in iso_lang:
604                     iso_lang2 = iso_lang.split('_')[0]
605                     f2 = modules.get_module_resource(mod.name, 'i18n', iso_lang2 + '.po')
606                     if f2:
607                         _logger.info('module %s: loading base translation file %s for language %s', mod.name, iso_lang2, lang)
608                         tools.trans_load(cr, f2, lang, verbose=False, context=context)
609                         context2['overwrite'] = True
610                 # Implementation notice: we must first search for the full name of
611                 # the language derivative, like "en_UK", and then the generic,
612                 # like "en".
613                 if (not f) and '_' in iso_lang:
614                     iso_lang = iso_lang.split('_')[0]
615                     f = modules.get_module_resource(mod.name, 'i18n', iso_lang + '.po')
616                 if f:
617                     _logger.info('module %s: loading translation file (%s) for language %s', mod.name, iso_lang, lang)
618                     tools.trans_load(cr, f, lang, verbose=False, context=context2)
619                 elif iso_lang != 'en':
620                     _logger.warning('module %s: no translation for language %s', mod.name, iso_lang)
621
622     def check(self, cr, uid, ids, context=None):
623         for mod in self.browse(cr, uid, ids, context=context):
624             if not mod.description:
625                 _logger.warning('module %s: description is empty !', mod.name)
626
627             if not mod.certificate or not mod.certificate.isdigit():
628                 _logger.info('module %s: no quality certificate', mod.name)
629             else:
630                 val = long(mod.certificate[2:]) % 97 == 29
631                 if not val:
632                     _logger.critical('module %s: invalid quality certificate: %s', mod.name, mod.certificate)
633                     raise osv.except_osv(_('Error'), _('Module %s: Invalid Quality Certificate') % (mod.name,))
634
635     def root_menus(self, cr, uid, ids, context=None):
636         """ Return root menu ids the menus created by the modules whose ids are
637         provided.
638
639         :param list[int] ids: modules to get menus from
640         """
641         values = self.read(cr, uid, ids, ['name'], context=context)
642         module_names = [i['name'] for i in values]
643
644         ids = self.pool.get('ir.model.data').search(cr, uid, [ ('model', '=', 'ir.ui.menu'), ('module', 'in', module_names) ], context=context)
645         values = self.pool.get('ir.model.data').read(cr, uid, ids, ['res_id'], context=context)
646         all_menu_ids = [i['res_id'] for i in values]
647
648         root_menu_ids = []
649         for menu in self.pool.get('ir.ui.menu').browse(cr, uid, all_menu_ids, context=context):
650             while menu.parent_id:
651                 menu = menu.parent_id
652             if not menu.id in root_menu_ids:
653                 root_menu_ids.append((menu.sequence,menu.id))
654         root_menu_ids.sort()
655         root_menu_ids = [i[1] for i in root_menu_ids]
656         return root_menu_ids
657
658 class module_dependency(osv.osv):
659     _name = "ir.module.module.dependency"
660     _description = "Module dependency"
661
662     def _state(self, cr, uid, ids, name, args, context=None):
663         result = {}
664         mod_obj = self.pool.get('ir.module.module')
665         for md in self.browse(cr, uid, ids):
666             ids = mod_obj.search(cr, uid, [('name', '=', md.name)])
667             if ids:
668                 result[md.id] = mod_obj.read(cr, uid, [ids[0]], ['state'])[0]['state']
669             else:
670                 result[md.id] = 'unknown'
671         return result
672
673     _columns = {
674         # The dependency name
675         'name': fields.char('Name',  size=128, select=True),
676
677         # The module that depends on it
678         'module_id': fields.many2one('ir.module.module', 'Module', select=True, ondelete='cascade'),
679
680         'state': fields.function(_state, type='selection', selection=[
681             ('uninstallable','Uninstallable'),
682             ('uninstalled','Not Installed'),
683             ('installed','Installed'),
684             ('to upgrade','To be upgraded'),
685             ('to remove','To be removed'),
686             ('to install','To be installed'),
687             ('unknown', 'Unknown'),
688             ], string='State', readonly=True, select=True),
689     }
690
691 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: