1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 ##############################################################################
23 from lxml import etree
27 import cPickle as pickle
32 from osv import fields, osv
33 from tools.translate import _
36 FIELD_STATES = [('clear', 'Clear'), ('anonymized', 'Anonymized'), ('not_existing', 'Not Existing')]
37 ANONYMIZATION_STATES = FIELD_STATES + [('unstable', 'Unstable')]
38 ANONYMIZATION_HISTORY_STATE = [('started', 'Started'), ('done', 'Done'), ('in_exception', 'Exception occured')]
39 ANONYMIZATION_DIRECTION = [('clear -> anonymized', 'clear -> anonymized'), ('anonymized -> clear', 'anonymized -> clear')]
42 class ir_model_fields_anonymization(osv.osv):
43 _name = 'ir.model.fields.anonymization'
44 _rec_name = 'field_id'
47 'model_name': fields.char('Object Name', size=128, required=True),
48 'model_id': fields.many2one('ir.model', 'Object', ondelete='set null'),
49 'field_name': fields.char('Field Name', size=128, required=True),
50 'field_id': fields.many2one('ir.model.fields', 'Field', ondelete='set null'),
51 'state': fields.selection(selection=FIELD_STATES, String='State', required=True, readonly=True),
55 ('model_id_field_id_uniq', 'unique (model_name, field_name)', _("You cannot have two records having the same model and the same field")),
58 def _get_global_state(self, cr, uid, context=None):
59 ids = self.search(cr, uid, [('state', '<>', 'not_existing')], context=context)
60 fields = self.browse(cr, uid, ids, context=context)
61 if not len(fields) or len(fields) == len([f for f in fields if f.state == 'clear']):
62 state = 'clear' # all fields are clear
63 elif len(fields) == len([f for f in fields if f.state == 'anonymized']):
64 state = 'anonymized' # all fields are anonymized
66 state = 'unstable' # fields are mixed: this should be fixed
69 def _check_write(self, cr, uid, context=None):
70 # check that the field is created from the menu and not from an database update
71 # otherwise the database update can crash:
72 if context.get('manual'):
73 global_state = self._get_global_state(cr, uid, context=context)
74 if global_state == 'anonymized':
75 raise osv.except_osv('Error !', "The database is currently anonymized, you cannot create, modify or delete fields.")
76 elif global_state == 'unstable':
77 msg = "The database anonymization is currently in an unstable state. Some fields are anonymized," + \
78 " while some fields are not anonymized. You should try to solve this problem before trying to create, write or delete fields."
79 raise osv.except_osv('Error !', msg)
83 def _get_model_and_field_ids(self, cr, uid, vals, context=None):
84 model_and_field_ids = (False, False)
86 if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']:
87 ir_model_fields_obj = self.pool.get('ir.model.fields')
88 ir_model_obj = self.pool.get('ir.model')
90 model_ids = ir_model_obj.search(cr, uid, [('model', '=', vals['model_name'])], context=context)
92 field_ids = ir_model_fields_obj.search(cr, uid, [('name', '=', vals['field_name']), ('model_id', '=', model_ids[0])], context=context)
94 field_id = field_ids[0]
95 model_and_field_ids = (model_ids[0], field_id)
97 return model_and_field_ids
99 def create(self, cr, uid, vals, context=None):
100 # check field state: all should be clear before we can add a new field to anonymize:
101 self._check_write(cr, uid, context=context)
103 if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']:
104 vals['model_id'], vals['field_id'] = self._get_model_and_field_ids(cr, uid, vals, context=context)
106 # check not existing fields:
107 if not vals.get('field_id'):
108 vals['state'] = 'not_existing'
110 res = super(ir_model_fields_anonymization, self).create(cr, uid, vals, context=context)
114 def write(self, cr, uid, ids, vals, context=None):
115 # check field state: all should be clear before we can modify a field:
116 if not (len(vals.keys()) == 1 and vals.get('state') == 'clear'):
117 self._check_write(cr, uid, context=context)
119 if 'field_name' in vals and vals['field_name'] and 'model_name' in vals and vals['model_name']:
120 vals['model_id'], vals['field_id'] = self._get_model_and_field_ids(cr, uid, vals, context=context)
122 # check not existing fields:
123 if 'field_id' in vals:
124 if not vals.get('field_id'):
125 vals['state'] = 'not_existing'
127 global_state = self._get_global_state(cr, uid, context)
128 if global_state != 'unstable':
129 vals['state'] = global_state
131 res = super(ir_model_fields_anonymization, self).write(cr, uid, ids, vals, context=context)
135 def unlink(self, cr, uid, ids, context=None):
136 # check field state: all should be clear before we can unlink a field:
137 self._check_write(cr, uid, context=context)
139 res = super(ir_model_fields_anonymization, self).unlink(cr, uid, ids, context=context)
142 def onchange_model_id(self, cr, uid, ids, model_id, context=None):
150 ir_model_obj = self.pool.get('ir.model')
151 model_ids = ir_model_obj.search(cr, uid, [('id', '=', model_id)])
152 model_id = model_ids and model_ids[0] or None
153 model_name = model_id and ir_model_obj.browse(cr, uid, model_id).model or False
154 res['value']['model_name'] = model_name
158 def onchange_model_name(self, cr, uid, ids, model_name, context=None):
166 ir_model_obj = self.pool.get('ir.model')
167 model_ids = ir_model_obj.search(cr, uid, [('model', '=', model_name)])
168 model_id = model_ids and model_ids[0] or False
169 res['value']['model_id'] = model_id
173 def onchange_field_name(self, cr, uid, ids, field_name, model_name):
178 if field_name and model_name:
179 ir_model_fields_obj = self.pool.get('ir.model.fields')
180 field_ids = ir_model_fields_obj.search(cr, uid, [('name', '=', field_name), ('model', '=', model_name)])
181 field_id = field_ids and field_ids[0] or False
182 res['value']['field_id'] = field_id
186 def onchange_field_id(self, cr, uid, ids, field_id, model_name):
192 ir_model_fields_obj = self.pool.get('ir.model.fields')
193 field = ir_model_fields_obj.browse(cr, uid, field_id)
194 res['value']['field_name'] = field.name
199 'state': lambda *a: 'clear',
202 ir_model_fields_anonymization()
205 class ir_model_fields_anonymization_history(osv.osv):
206 _name = 'ir.model.fields.anonymization.history'
210 'date': fields.datetime('Date', required=True, readonly=True),
211 'field_ids': fields.many2many('ir.model.fields.anonymization', 'anonymized_field_to_history_rel', 'field_id', 'history_id', 'Fields', readonly=True),
212 'state': fields.selection(selection=ANONYMIZATION_HISTORY_STATE, string='State', required=True, readonly=True),
213 'direction': fields.selection(selection=ANONYMIZATION_DIRECTION, string='Direction', required=True, readonly=True),
214 'msg': fields.text('Message', readonly=True),
215 'filepath': fields.char(string='File path', size=256, readonly=True),
218 ir_model_fields_anonymization_history()
221 class ir_model_fields_anonymize_wizard(osv.osv_memory):
222 _name = 'ir.model.fields.anonymize.wizard'
224 def _get_state(self, cr, uid, ids, name, arg, context=None):
227 state = self._get_state_value(cr, uid, context=None)
233 def _get_summary(self, cr, uid, ids, name, arg, context=None):
235 summary = self._get_summary_value(cr, uid, context)
242 'name': fields.char(size='64', string='File Name'),
243 'summary': fields.function(_get_summary, method=True, type='text', string='Summary'),
244 'file_export': fields.binary(string='Export'),
245 'file_import': fields.binary(string='Import'),
246 'state': fields.function(_get_state, method=True, string='State', type='selection', selection=ANONYMIZATION_STATES, readonly=False),
247 'msg': fields.text(string='Message'),
250 def _get_state_value(self, cr, uid, context=None):
251 state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context)
254 def _get_summary_value(self, cr, uid, context=None):
256 anon_field_obj = self.pool.get('ir.model.fields.anonymization')
257 ir_model_fields_obj = self.pool.get('ir.model.fields')
259 anon_field_ids = anon_field_obj.search(cr, uid, [('state', '<>', 'not_existing')], context=context)
260 anon_fields = anon_field_obj.browse(cr, uid, anon_field_ids, context=context)
262 field_ids = [anon_field.field_id.id for anon_field in anon_fields if anon_field.field_id]
263 fields = ir_model_fields_obj.browse(cr, uid, field_ids, context=context)
265 fields_by_id = dict([(f.id, f) for f in fields])
267 for anon_field in anon_fields:
268 field = fields_by_id.get(anon_field.field_id.id)
271 'model_name': field.model_id.name,
272 'model_code': field.model_id.model,
273 'field_code': field.name,
274 'field_name': field.field_description,
275 'state': anon_field.state,
277 summary += u" * %(model_name)s (%(model_code)s) -> %(field_name)s (%(field_code)s): state: (%(state)s)\n" % values
281 def default_get(self, cr, uid, fields_list, context=None):
283 res['name'] = '.pickle'
284 res['summary'] = self._get_summary_value(cr, uid, context)
285 res['state'] = self._get_state_value(cr, uid, context)
286 res['msg'] = """Before executing the anonymization process, you should make a backup of your database."""
290 def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, *args, **kwargs):
291 state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context)
292 step = context.get('step', 'new_window')
294 res = super(ir_model_fields_anonymize_wizard, self).fields_view_get(cr, uid, view_id, view_type, context, *args, **kwargs)
296 eview = etree.fromstring(res['arch'])
297 placeholder = eview.xpath("group[@name='placeholder1']")
299 placeholder = placeholder[0]
300 if step == 'new_window' and state == 'clear':
301 # clicked in the menu and the fields are not anonymized: warn the admin that backuping the db is very important
302 placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'}))
303 placeholder.addnext(etree.Element('newline'))
304 placeholder.addnext(etree.Element('label', {'string': 'Warning'}))
305 eview.remove(placeholder)
306 elif step == 'new_window' and state == 'anonymized':
307 # clicked in the menu and the fields are already anonymized
308 placeholder.addnext(etree.Element('newline'))
309 placeholder.addnext(etree.Element('field', {'name': 'file_import', 'required': "1"}))
310 eview.remove(placeholder)
311 elif step == 'just_anonymized':
312 # we just ran the anonymization process, we need the file export field
313 placeholder.addnext(etree.Element('newline'))
314 placeholder.addnext(etree.Element('field', {'name': 'file_export'}))
315 # we need to remove the button:
316 buttons = eview.xpath("button")
317 for button in buttons:
320 placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'}))
321 placeholder.addnext(etree.Element('newline'))
322 placeholder.addnext(etree.Element('label', {'string': 'Result'}))
323 # remove the placeholer:
324 eview.remove(placeholder)
325 elif step == 'just_desanonymized':
326 # we just reversed the anonymization process, we don't need any field
327 # we need to remove the button
328 buttons = eview.xpath("button")
329 for button in buttons:
333 placeholder.addnext(etree.Element('field', {'name': 'msg', 'colspan': '4', 'nolabel': '1'}))
334 placeholder.addnext(etree.Element('newline'))
335 placeholder.addnext(etree.Element('label', {'string': 'Result'}))
336 # remove the placeholer:
337 eview.remove(placeholder)
342 res['arch'] = etree.tostring(eview)
346 def _raise_after_history_update(self, cr, uid, history_id, error_type, error_msg):
347 self.pool.get('ir.model.fields.anonymization.history').write(cr, uid, history_id, {
348 'state': 'in_exception',
351 raise osv.except_osv(error_type, error_msg)
353 def anonymize_database(self,cr, uid, ids, context=None):
354 """Sets the 'anonymized' state to defined fields"""
356 # create a new history record:
357 anonymization_history_model = self.pool.get('ir.model.fields.anonymization.history')
360 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
362 'direction': 'clear -> anonymized',
364 history_id = anonymization_history_model.create(cr, uid, vals)
366 # check that all the defined fields are in the 'clear' state
367 state = self.pool.get('ir.model.fields.anonymization')._get_global_state(cr, uid, context=context)
368 if state == 'anonymized':
369 self._raise_after_history_update(cr, uid, history_id, 'Error !', "The database is currently anonymized, you cannot anonymize it again.")
370 elif state == 'unstable':
371 msg = "The database anonymization is currently in an unstable state. Some fields are anonymized," + \
372 " while some fields are not anonymized. You should try to solve this problem before trying to do anything."
373 self._raise_after_history_update(cr, uid, history_id, 'Error !', msg)
375 # do the anonymization:
376 dirpath = os.environ.get('HOME') or os.getcwd()
377 rel_filepath = 'field_anonymization_%s_%s.pickle' % (cr.dbname, history_id)
378 abs_filepath = os.path.abspath(os.path.join(dirpath, rel_filepath))
380 ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization')
381 field_ids = ir_model_fields_anonymization_model.search(cr, uid, [('state', '<>', 'not_existing')], context=context)
382 fields = ir_model_fields_anonymization_model.browse(cr, uid, field_ids, context=context)
385 msg = "No fields are going to be anonymized."
386 self._raise_after_history_update(cr, uid, history_id, 'Error !', msg)
391 model_name = field.model_id.model
392 field_name = field.field_id.name
393 field_type = field.field_id.ttype
394 table_name = self.pool.get(model_name)._table
396 # get the current value
397 sql = "select id, %s from %s" % (field_name, table_name)
399 records = cr.dictfetchall()
400 for record in records:
401 data.append({"model_id": model_name, "field_id": field_name, "id": record['id'], "value": record[field_name]})
403 # anonymize the value:
404 anonymized_value = None
406 sid = str(record['id'])
407 if field_type == 'char':
408 anonymized_value = 'xxx'+sid
409 elif field_type == 'selection':
410 anonymized_value = 'xxx'+sid
411 elif field_type == 'text':
412 anonymized_value = 'xxx'+sid
413 elif field_type == 'boolean':
414 anonymized_value = random.choice([True, False])
415 elif field_type == 'date':
416 anonymized_value = '2011-11-11'
417 elif field_type == 'datetime':
418 anonymized_value = '2011-11-11 11:11:11'
419 elif field_type == 'float':
420 anonymized_value = 0.0
421 elif field_type == 'integer':
423 elif field_type in ['binary', 'many2many', 'many2one', 'one2many', 'reference']: # cannot anonymize these kind of fields
424 msg = "Cannot anonymize fields of these types: binary, many2many, many2one, one2many, reference"
425 self._raise_after_history_update(cr, uid, history_id, 'Error !', msg)
427 if anonymized_value is None:
428 self._raise_after_history_update(cr, uid, history_id, 'Error !', "Anonymized value is None. This cannot happens.")
430 sql = "update %(table)s set %(field)s = %%(anonymized_value)s where id = %%(id)s" % {
435 'anonymized_value': anonymized_value,
440 fn = open(abs_filepath, 'w')
441 pickle.dump(data, fn, pickle.HIGHEST_PROTOCOL)
443 # update the anonymization fields:
445 'state': 'anonymized',
447 ir_model_fields_anonymization_model.write(cr, uid, field_ids, values, context=context)
449 # add a result message in the wizard:
450 msgs = ["Anonymization successful.",
452 "Don't forget to save the resulting file to a safe place because you will not be able to revert the anonymization without this file.",
454 "This file is also stored in the %s directory. The absolute file path is: %s",
456 msg = '\n'.join(msgs) % (dirpath, abs_filepath)
458 fn = open(abs_filepath, 'r')
460 self.write(cr, uid, ids, {
462 'file_export': base64.encodestring(fn.read()),
466 # update the history record:
467 anonymization_history_model.write(cr, uid, history_id, {
468 'field_ids': [[6, 0, field_ids]],
470 'filepath': abs_filepath,
475 view_id = self._id_get(cr, uid, 'ir.ui.view', 'view_ir_model_fields_anonymize_wizard_form', 'anonymization')
479 'view_id': [view_id],
482 'res_model': 'ir.model.fields.anonymize.wizard',
483 'type': 'ir.actions.act_window',
484 'context': {'step': 'just_anonymized'},
488 def reverse_anonymize_database(self,cr, uid, ids, context=None):
489 """Set the 'clear' state to defined fields"""
491 ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization')
492 anonymization_history_model = self.pool.get('ir.model.fields.anonymization.history')
494 # create a new history record:
496 'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
498 'direction': 'anonymized -> clear',
500 history_id = anonymization_history_model.create(cr, uid, vals)
502 # check that all the defined fields are in the 'anonymized' state
503 state = ir_model_fields_anonymization_model._get_global_state(cr, uid, context=context)
505 raise osv.except_osv('Error !', "The database is not currently anonymized, you cannot reverse the anonymization.")
506 elif state == 'unstable':
507 msg = "The database anonymization is currently in an unstable state. Some fields are anonymized," + \
508 " while some fields are not anonymized. You should try to solve this problem before trying to do anything."
509 raise osv.except_osv('Error !', msg)
511 wizards = self.browse(cr, uid, ids, context=context)
512 for wizard in wizards:
513 if not wizard.file_import:
514 msg = "The anonymization export file was not supplied. It is not possible to reverse the anonymization process without this file."
515 self._raise_after_history_update(cr, uid, history_id, 'Error !', msg)
517 # reverse the anonymization:
518 # load the pickle file content into a data structure:
519 data = pickle.loads(base64.decodestring(wizard.file_import))
522 table_name = self.pool.get(line['model_id'])._table
523 sql = "update %(table)s set %(field)s = %%(value)s where id = %%(id)s" % {
525 'field': line['field_id'],
528 'value': line['value'],
532 # update the anonymization fields:
533 ir_model_fields_anonymization_model = self.pool.get('ir.model.fields.anonymization')
534 field_ids = ir_model_fields_anonymization_model.search(cr, uid, [('state', '<>', 'not_existing')], context=context)
538 ir_model_fields_anonymization_model.write(cr, uid, field_ids, values, context=context)
540 # add a result message in the wizard:
541 msg = '\n'.join(["Successfully reversed the anonymization.",
545 self.write(cr, uid, ids, {'msg': msg})
547 # update the history record:
548 anonymization_history_model.write(cr, uid, history_id, {
549 'field_ids': [[6, 0, field_ids]],
556 view_id = self._id_get(cr, uid, 'ir.ui.view', 'view_ir_model_fields_anonymize_wizard_form', 'anonymization')
560 'view_id': [view_id],
563 'res_model': 'ir.model.fields.anonymize.wizard',
564 'type': 'ir.actions.act_window',
565 'context': {'step': 'just_desanonymized'},
569 def _id_get(self, cr, uid, model, id_str, mod):
571 mod, id_str = id_str.split('.')
573 idn = self.pool.get('ir.model.data')._get_id(cr, uid, mod, id_str)
574 res = int(self.pool.get('ir.model.data').read(cr, uid, [idn], ['res_id'])[0]['res_id'])
579 ir_model_fields_anonymize_wizard()