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.

592 lines
25 KiB

10 years ago
10 years ago
10 years ago
  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. # Copyright (C) 2013 ABF OSIELL (<http://osiell.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. from openerp import models, fields, api, modules, _, SUPERUSER_ID, sql_db
  22. FIELDS_BLACKLIST = [
  23. 'id', 'create_uid', 'create_date', 'write_uid', 'write_date',
  24. 'display_name', '__last_update',
  25. ]
  26. # Used for performance, to avoid a dictionary instanciation when we need an
  27. # empty dict to simplify algorithms
  28. EMPTY_DICT = {}
  29. class DictDiffer(object):
  30. """Calculate the difference between two dictionaries as:
  31. (1) items added
  32. (2) items removed
  33. (3) keys same in both but changed values
  34. (4) keys same in both and unchanged values
  35. """
  36. def __init__(self, current_dict, past_dict):
  37. self.current_dict, self.past_dict = current_dict, past_dict
  38. self.set_current = set(current_dict)
  39. self.set_past = set(past_dict)
  40. self.intersect = self.set_current.intersection(self.set_past)
  41. def added(self):
  42. return self.set_current - self.intersect
  43. def removed(self):
  44. return self.set_past - self.intersect
  45. def changed(self):
  46. return set(o for o in self.intersect
  47. if self.past_dict[o] != self.current_dict[o])
  48. def unchanged(self):
  49. return set(o for o in self.intersect
  50. if self.past_dict[o] == self.current_dict[o])
  51. class AuditlogRule(models.Model):
  52. _name = 'auditlog.rule'
  53. _description = "Auditlog - Rule"
  54. name = fields.Char(u"Name", size=32, required=True)
  55. model_id = fields.Many2one(
  56. 'ir.model', u"Model", required=True,
  57. help=u"Select model for which you want to generate log.")
  58. user_ids = fields.Many2many(
  59. 'res.users',
  60. 'audittail_rules_users',
  61. 'user_id', 'rule_id',
  62. string=u"Users",
  63. help=u"if User is not added then it will applicable for all users")
  64. log_read = fields.Boolean(
  65. u"Log Reads",
  66. help=(u"Select this if you want to keep track of read/open on any "
  67. u"record of the model of this rule"))
  68. log_write = fields.Boolean(
  69. u"Log Writes", default=True,
  70. help=(u"Select this if you want to keep track of modification on any "
  71. u"record of the model of this rule"))
  72. log_unlink = fields.Boolean(
  73. u"Log Deletes", default=True,
  74. help=(u"Select this if you want to keep track of deletion on any "
  75. u"record of the model of this rule"))
  76. log_create = fields.Boolean(
  77. u"Log Creates", default=True,
  78. help=(u"Select this if you want to keep track of creation on any "
  79. u"record of the model of this rule"))
  80. log_type = fields.Selection(
  81. [('full', u"Full log"),
  82. ('fast', u"Fast log"),
  83. ],
  84. string=u"Type", required=True, default='full',
  85. help=(u"Full log: make a diff between the data before and after "
  86. u"the operation (log more info like computed fields which were "
  87. u"updated, but it is slower)\n"
  88. u"Fast log: only log the changes made through the create and "
  89. u"write operations (less information, but it is faster)"))
  90. # log_action = fields.Boolean(
  91. # "Log Action",
  92. # help=("Select this if you want to keep track of actions on the "
  93. # "model of this rule"))
  94. # log_workflow = fields.Boolean(
  95. # "Log Workflow",
  96. # help=("Select this if you want to keep track of workflow on any "
  97. # "record of the model of this rule"))
  98. state = fields.Selection(
  99. [('draft', "Draft"), ('subscribed', "Subscribed")],
  100. string=u"State", required=True, default='draft')
  101. action_id = fields.Many2one(
  102. 'ir.actions.act_window', string="Action")
  103. _sql_constraints = [
  104. ('model_uniq', 'unique(model_id)',
  105. ("There is already a rule defined on this model\n"
  106. "You cannot define another: please edit the existing one."))
  107. ]
  108. def _register_hook(self, cr, ids=None):
  109. """Get all rules and apply them to log method calls."""
  110. super(AuditlogRule, self)._register_hook(cr)
  111. if not hasattr(self.pool, '_auditlog_field_cache'):
  112. self.pool._auditlog_field_cache = {}
  113. if not hasattr(self.pool, '_auditlog_model_cache'):
  114. self.pool._auditlog_model_cache = {}
  115. if ids is None:
  116. ids = self.search(cr, SUPERUSER_ID, [('state', '=', 'subscribed')])
  117. return self._patch_methods(cr, SUPERUSER_ID, ids)
  118. @api.multi
  119. def _patch_methods(self):
  120. """Patch ORM methods of models defined in rules to log their calls."""
  121. updated = False
  122. model_cache = self.pool._auditlog_model_cache
  123. for rule in self:
  124. if rule.state != 'subscribed':
  125. continue
  126. if not self.pool.get(rule.model_id.model):
  127. # ignore rules for models not loadable currently
  128. continue
  129. model_cache[rule.model_id.model] = rule.model_id.id
  130. model_model = self.env[rule.model_id.model]
  131. # CRUD
  132. # -> create
  133. check_attr = 'auditlog_ruled_create'
  134. if getattr(rule, 'log_create') \
  135. and not hasattr(model_model, check_attr):
  136. model_model._patch_method('create', rule._make_create())
  137. setattr(model_model, check_attr, True)
  138. updated = True
  139. # -> read
  140. check_attr = 'auditlog_ruled_read'
  141. if getattr(rule, 'log_read') \
  142. and not hasattr(model_model, check_attr):
  143. model_model._patch_method('read', rule._make_read())
  144. setattr(model_model, check_attr, True)
  145. updated = True
  146. # -> write
  147. check_attr = 'auditlog_ruled_write'
  148. if getattr(rule, 'log_write') \
  149. and not hasattr(model_model, check_attr):
  150. model_model._patch_method('write', rule._make_write())
  151. setattr(model_model, check_attr, True)
  152. updated = True
  153. # -> unlink
  154. check_attr = 'auditlog_ruled_unlink'
  155. if getattr(rule, 'log_unlink') \
  156. and not hasattr(model_model, check_attr):
  157. model_model._patch_method('unlink', rule._make_unlink())
  158. setattr(model_model, check_attr, True)
  159. updated = True
  160. return updated
  161. @api.multi
  162. def _revert_methods(self):
  163. """Restore original ORM methods of models defined in rules."""
  164. updated = False
  165. for rule in self:
  166. model_model = self.env[rule.model_id.model]
  167. for method in ['create', 'read', 'write', 'unlink']:
  168. if getattr(rule, 'log_%s' % method) and hasattr(
  169. getattr(model_model, method), 'origin'):
  170. model_model._revert_method(method)
  171. updated = True
  172. if updated:
  173. modules.registry.RegistryManager.signal_registry_change(
  174. self.env.cr.dbname)
  175. # Unable to find a way to declare the `create` method with the new API,
  176. # errors occurs with the `_register_hook()` BaseModel method.
  177. def create(self, cr, uid, vals, context=None):
  178. """Update the registry when a new rule is created."""
  179. res_id = super(AuditlogRule, self).create(
  180. cr, uid, vals, context=context)
  181. if self._register_hook(cr, [res_id]):
  182. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  183. return res_id
  184. # Unable to find a way to declare the `write` method with the new API,
  185. # errors occurs with the `_register_hook()` BaseModel method.
  186. def write(self, cr, uid, ids, vals, context=None):
  187. """Update the registry when existing rules are updated."""
  188. if isinstance(ids, (int, long)):
  189. ids = [ids]
  190. super(AuditlogRule, self).write(cr, uid, ids, vals, context=context)
  191. if self._register_hook(cr, ids):
  192. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  193. return True
  194. @api.multi
  195. def unlink(self):
  196. """Unsubscribe rules before removing them."""
  197. self.unsubscribe()
  198. return super(AuditlogRule, self).unlink()
  199. @api.multi
  200. def _make_create(self):
  201. """Instanciate a create method that log its calls."""
  202. self.ensure_one()
  203. log_type = self.log_type
  204. @api.model
  205. @api.returns('self', lambda value: value.id)
  206. def create_full(self, vals, **kwargs):
  207. self = self.with_context(auditlog_disabled=True)
  208. rule_model = self.env['auditlog.rule']
  209. new_record = create_full.origin(self, vals, **kwargs)
  210. new_values = dict(
  211. (d['id'], d) for d in new_record.sudo()
  212. .with_context(prefetch_fields=False).read(list(self._fields)))
  213. rule_model.sudo().create_logs(
  214. self.env.uid, self._name, new_record.ids,
  215. 'create', None, new_values, {'log_type': log_type})
  216. return new_record
  217. @api.model
  218. @api.returns('self', lambda value: value.id)
  219. def create_fast(self, vals, **kwargs):
  220. self = self.with_context(auditlog_disabled=True)
  221. rule_model = self.env['auditlog.rule']
  222. vals2 = dict(vals)
  223. new_record = create_fast.origin(self, vals, **kwargs)
  224. new_values = {new_record.id: vals2}
  225. rule_model.sudo().create_logs(
  226. self.env.uid, self._name, new_record.ids,
  227. 'create', None, new_values, {'log_type': log_type})
  228. return new_record
  229. return create_full if self.log_type == 'full' else create_fast
  230. @api.multi
  231. def _make_read(self):
  232. """Instanciate a read method that log its calls."""
  233. self.ensure_one()
  234. log_type = self.log_type
  235. def read(self, *args, **kwargs):
  236. result = read.origin(self, *args, **kwargs)
  237. # Sometimes the result is not a list but a dictionary
  238. # Also, we can not modify the current result as it will break calls
  239. result2 = result
  240. if not isinstance(result2, list):
  241. result2 = [result]
  242. read_values = dict((d['id'], d) for d in result2)
  243. # Old API
  244. if args and isinstance(args[0], sql_db.Cursor):
  245. cr, uid, ids = args[0], args[1], args[2]
  246. if isinstance(ids, (int, long)):
  247. ids = [ids]
  248. # If the call came from auditlog itself, skip logging:
  249. # avoid logs on `read` produced by auditlog during internal
  250. # processing: read data of relevant records, 'ir.model',
  251. # 'ir.model.fields'... (no interest in logging such operations)
  252. if kwargs.get('context', {}).get('auditlog_disabled'):
  253. return result
  254. env = api.Environment(cr, uid, {'auditlog_disabled': True})
  255. rule_model = env['auditlog.rule']
  256. rule_model.sudo().create_logs(
  257. env.uid, self._name, ids,
  258. 'read', read_values, None, {'log_type': log_type})
  259. # New API
  260. else:
  261. # If the call came from auditlog itself, skip logging:
  262. # avoid logs on `read` produced by auditlog during internal
  263. # processing: read data of relevant records, 'ir.model',
  264. # 'ir.model.fields'... (no interest in logging such operations)
  265. if self.env.context.get('auditlog_disabled'):
  266. return result
  267. self = self.with_context(auditlog_disabled=True)
  268. rule_model = self.env['auditlog.rule']
  269. rule_model.sudo().create_logs(
  270. self.env.uid, self._name, self.ids,
  271. 'read', read_values, None, {'log_type': log_type})
  272. return result
  273. return read
  274. @api.multi
  275. def _make_write(self):
  276. """Instanciate a write method that log its calls."""
  277. self.ensure_one()
  278. log_type = self.log_type
  279. @api.multi
  280. def write_full(self, vals, **kwargs):
  281. self = self.with_context(auditlog_disabled=True)
  282. rule_model = self.env['auditlog.rule']
  283. old_values = dict(
  284. (d['id'], d) for d in self.sudo()
  285. .with_context(prefetch_fields=False).read(list(self._fields)))
  286. result = write_full.origin(self, vals, **kwargs)
  287. new_values = dict(
  288. (d['id'], d) for d in self.sudo()
  289. .with_context(prefetch_fields=False).read(list(self._fields)))
  290. rule_model.sudo().create_logs(
  291. self.env.uid, self._name, self.ids,
  292. 'write', old_values, new_values, {'log_type': log_type})
  293. return result
  294. @api.multi
  295. def write_fast(self, vals, **kwargs):
  296. self = self.with_context(auditlog_disabled=True)
  297. rule_model = self.env['auditlog.rule']
  298. # Log the user input only, no matter if the `vals` is updated
  299. # afterwards as it could not represent the real state
  300. # of the data in the database
  301. vals2 = dict(vals)
  302. old_vals2 = dict.fromkeys(vals2.keys(), False)
  303. old_values = dict((id_, old_vals2) for id_ in self.ids)
  304. new_values = dict((id_, vals2) for id_ in self.ids)
  305. result = write_fast.origin(self, vals, **kwargs)
  306. rule_model.sudo().create_logs(
  307. self.env.uid, self._name, self.ids,
  308. 'write', old_values, new_values, {'log_type': log_type})
  309. return result
  310. return write_full if self.log_type == 'full' else write_fast
  311. @api.multi
  312. def _make_unlink(self):
  313. """Instanciate an unlink method that log its calls."""
  314. self.ensure_one()
  315. log_type = self.log_type
  316. @api.multi
  317. def unlink_full(self, **kwargs):
  318. self = self.with_context(auditlog_disabled=True)
  319. rule_model = self.env['auditlog.rule']
  320. old_values = dict(
  321. (d['id'], d) for d in self.sudo()
  322. .with_context(prefetch_fields=False).read(list(self._fields)))
  323. rule_model.sudo().create_logs(
  324. self.env.uid, self._name, self.ids, 'unlink', old_values, None,
  325. {'log_type': log_type})
  326. return unlink_full.origin(self, **kwargs)
  327. @api.multi
  328. def unlink_fast(self, **kwargs):
  329. self = self.with_context(auditlog_disabled=True)
  330. rule_model = self.env['auditlog.rule']
  331. rule_model.sudo().create_logs(
  332. self.env.uid, self._name, self.ids, 'unlink', None, None,
  333. {'log_type': log_type})
  334. return unlink_fast.origin(self, **kwargs)
  335. return unlink_full if self.log_type == 'full' else unlink_fast
  336. def create_logs(self, uid, res_model, res_ids, method,
  337. old_values=None, new_values=None,
  338. additional_log_values=None):
  339. """Create logs. `old_values` and `new_values` are dictionnaries, e.g:
  340. {RES_ID: {'FIELD': VALUE, ...}}
  341. """
  342. if old_values is None:
  343. old_values = EMPTY_DICT
  344. if new_values is None:
  345. new_values = EMPTY_DICT
  346. log_model = self.env['auditlog.log']
  347. http_request_model = self.env['auditlog.http.request']
  348. http_session_model = self.env['auditlog.http.session']
  349. for res_id in res_ids:
  350. model_model = self.env[res_model]
  351. name = model_model.browse(res_id).name_get()
  352. res_name = name and name[0] and name[0][1]
  353. vals = {
  354. 'name': res_name,
  355. 'model_id': self.pool._auditlog_model_cache[res_model],
  356. 'res_id': res_id,
  357. 'method': method,
  358. 'user_id': uid,
  359. 'http_request_id': http_request_model.current_http_request(),
  360. 'http_session_id': http_session_model.current_http_session(),
  361. }
  362. vals.update(additional_log_values or {})
  363. log = log_model.create(vals)
  364. diff = DictDiffer(
  365. new_values.get(res_id, EMPTY_DICT),
  366. old_values.get(res_id, EMPTY_DICT))
  367. if method is 'create':
  368. self._create_log_line_on_create(log, diff.added(), new_values)
  369. elif method is 'read':
  370. self._create_log_line_on_read(
  371. log, old_values.get(res_id, EMPTY_DICT).keys(), old_values)
  372. elif method is 'write':
  373. self._create_log_line_on_write(
  374. log, diff.changed(), old_values, new_values)
  375. def _get_field(self, model, field_name):
  376. cache = self.pool._auditlog_field_cache
  377. if field_name not in cache.get(model.model, {}):
  378. cache.setdefault(model.model, {})
  379. # - we use 'search()' then 'read()' instead of the 'search_read()'
  380. # to take advantage of the 'classic_write' loading
  381. # - search the field in the current model and those it inherits
  382. field_model = self.env['ir.model.fields']
  383. all_model_ids = [model.id]
  384. all_model_ids.extend(model.inherited_model_ids.ids)
  385. field = field_model.search(
  386. [('model_id', 'in', all_model_ids), ('name', '=', field_name)])
  387. # The field can be a dummy one, like 'in_group_X' on 'res.users'
  388. # As such we can't log it (field_id is required to create a log)
  389. if not field:
  390. cache[model.model][field_name] = False
  391. else:
  392. field_data = field.read(load='_classic_write')[0]
  393. cache[model.model][field_name] = field_data
  394. return cache[model.model][field_name]
  395. def _create_log_line_on_read(
  396. self, log, fields_list, read_values):
  397. """Log field filled on a 'read' operation."""
  398. log_line_model = self.env['auditlog.log.line']
  399. for field_name in fields_list:
  400. if field_name in FIELDS_BLACKLIST:
  401. continue
  402. field = self._get_field(log.model_id, field_name)
  403. # not all fields have an ir.models.field entry (ie. related fields)
  404. if field:
  405. log_vals = self._prepare_log_line_vals_on_read(
  406. log, field, read_values)
  407. log_line_model.create(log_vals)
  408. def _prepare_log_line_vals_on_read(self, log, field, read_values):
  409. """Prepare the dictionary of values used to create a log line on a
  410. 'read' operation.
  411. """
  412. vals = {
  413. 'field_id': field['id'],
  414. 'log_id': log.id,
  415. 'old_value': read_values[log.res_id][field['name']],
  416. 'old_value_text': read_values[log.res_id][field['name']],
  417. 'new_value': False,
  418. 'new_value_text': False,
  419. }
  420. if field['relation'] and '2many' in field['ttype']:
  421. old_value_text = self.env[field['relation']].browse(
  422. vals['old_value']).name_get()
  423. vals['old_value_text'] = old_value_text
  424. return vals
  425. def _create_log_line_on_write(
  426. self, log, fields_list, old_values, new_values):
  427. """Log field updated on a 'write' operation."""
  428. log_line_model = self.env['auditlog.log.line']
  429. for field_name in fields_list:
  430. if field_name in FIELDS_BLACKLIST:
  431. continue
  432. field = self._get_field(log.model_id, field_name)
  433. # not all fields have an ir.models.field entry (ie. related fields)
  434. if field:
  435. log_vals = self._prepare_log_line_vals_on_write(
  436. log, field, old_values, new_values)
  437. log_line_model.create(log_vals)
  438. def _prepare_log_line_vals_on_write(
  439. self, log, field, old_values, new_values):
  440. """Prepare the dictionary of values used to create a log line on a
  441. 'write' operation.
  442. """
  443. vals = {
  444. 'field_id': field['id'],
  445. 'log_id': log.id,
  446. 'old_value': old_values[log.res_id][field['name']],
  447. 'old_value_text': old_values[log.res_id][field['name']],
  448. 'new_value': new_values[log.res_id][field['name']],
  449. 'new_value_text': new_values[log.res_id][field['name']],
  450. }
  451. # for *2many fields, log the name_get
  452. if log.log_type == 'full' and field['relation'] \
  453. and '2many' in field['ttype']:
  454. # Filter IDs to prevent a 'name_get()' call on deleted resources
  455. existing_ids = self.env[field['relation']]._search(
  456. [('id', 'in', vals['old_value'])])
  457. old_value_text = []
  458. if existing_ids:
  459. existing_values = self.env[field['relation']].browse(
  460. existing_ids).name_get()
  461. old_value_text.extend(existing_values)
  462. # Deleted resources will have a 'DELETED' text representation
  463. deleted_ids = set(vals['old_value']) - set(existing_ids)
  464. for deleted_id in deleted_ids:
  465. old_value_text.append((deleted_id, 'DELETED'))
  466. vals['old_value_text'] = old_value_text
  467. new_value_text = self.env[field['relation']].browse(
  468. vals['new_value']).name_get()
  469. vals['new_value_text'] = new_value_text
  470. return vals
  471. def _create_log_line_on_create(
  472. self, log, fields_list, new_values):
  473. """Log field filled on a 'create' operation."""
  474. log_line_model = self.env['auditlog.log.line']
  475. for field_name in fields_list:
  476. if field_name in FIELDS_BLACKLIST:
  477. continue
  478. field = self._get_field(log.model_id, field_name)
  479. # not all fields have an ir.models.field entry (ie. related fields)
  480. if field:
  481. log_vals = self._prepare_log_line_vals_on_create(
  482. log, field, new_values)
  483. log_line_model.create(log_vals)
  484. def _prepare_log_line_vals_on_create(self, log, field, new_values):
  485. """Prepare the dictionary of values used to create a log line on a
  486. 'create' operation.
  487. """
  488. vals = {
  489. 'field_id': field['id'],
  490. 'log_id': log.id,
  491. 'old_value': False,
  492. 'old_value_text': False,
  493. 'new_value': new_values[log.res_id][field['name']],
  494. 'new_value_text': new_values[log.res_id][field['name']],
  495. }
  496. if log.log_type == 'full' and field['relation'] \
  497. and '2many' in field['ttype']:
  498. new_value_text = self.env[field['relation']].browse(
  499. vals['new_value']).name_get()
  500. vals['new_value_text'] = new_value_text
  501. return vals
  502. @api.multi
  503. def subscribe(self):
  504. """Subscribe Rule for auditing changes on model and apply shortcut
  505. to view logs on that model.
  506. """
  507. act_window_model = self.env['ir.actions.act_window']
  508. model_data_model = self.env['ir.model.data']
  509. for rule in self:
  510. # Create a shortcut to view logs
  511. domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
  512. rule.model_id.id)
  513. vals = {
  514. 'name': _(u"View logs"),
  515. 'res_model': 'auditlog.log',
  516. 'src_model': rule.model_id.model,
  517. 'domain': domain,
  518. }
  519. act_window = act_window_model.sudo().create(vals)
  520. rule.write({'state': 'subscribed', 'action_id': act_window.id})
  521. keyword = 'client_action_relate'
  522. value = 'ir.actions.act_window,%s' % act_window.id
  523. model_data_model.sudo().ir_set(
  524. 'action', keyword, 'View_log_' + rule.model_id.model,
  525. [rule.model_id.model], value, replace=True,
  526. isobject=True, xml_id=False)
  527. return True
  528. @api.multi
  529. def unsubscribe(self):
  530. """Unsubscribe Auditing Rule on model."""
  531. act_window_model = self.env['ir.actions.act_window']
  532. ir_values_model = self.env['ir.values']
  533. # Revert patched methods
  534. self._revert_methods()
  535. for rule in self:
  536. # Remove the shortcut to view logs
  537. act_window = act_window_model.search(
  538. [('name', '=', 'View Log'),
  539. ('res_model', '=', 'auditlog.log'),
  540. ('src_model', '=', rule.model_id.model)])
  541. if act_window:
  542. value = 'ir.actions.act_window,%s' % act_window.id
  543. act_window.unlink()
  544. ir_value = ir_values_model.search(
  545. [('model', '=', rule.model_id.model),
  546. ('value', '=', value)])
  547. if ir_value:
  548. ir_value.unlink()
  549. self.write({'state': 'draft'})
  550. return True