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.

522 lines
22 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_action = fields.Boolean(
  81. # "Log Action",
  82. # help=("Select this if you want to keep track of actions on the "
  83. # "model of this rule"))
  84. # log_workflow = fields.Boolean(
  85. # "Log Workflow",
  86. # help=("Select this if you want to keep track of workflow on any "
  87. # "record of the model of this rule"))
  88. state = fields.Selection(
  89. [('draft', "Draft"), ('subscribed', "Subscribed")],
  90. string=u"State", required=True, default='draft')
  91. action_id = fields.Many2one(
  92. 'ir.actions.act_window', string="Action")
  93. _sql_constraints = [
  94. ('model_uniq', 'unique(model_id)',
  95. ("There is already a rule defined on this model\n"
  96. "You cannot define another: please edit the existing one."))
  97. ]
  98. def _register_hook(self, cr, ids=None):
  99. """Get all rules and apply them to log method calls."""
  100. super(AuditlogRule, self)._register_hook(cr)
  101. if not hasattr(self.pool, '_auditlog_field_cache'):
  102. self.pool._auditlog_field_cache = {}
  103. if not hasattr(self.pool, '_auditlog_model_cache'):
  104. self.pool._auditlog_model_cache = {}
  105. if ids is None:
  106. ids = self.search(cr, SUPERUSER_ID, [('state', '=', 'subscribed')])
  107. return self._patch_methods(cr, SUPERUSER_ID, ids)
  108. @api.multi
  109. def _patch_methods(self):
  110. """Patch ORM methods of models defined in rules to log their calls."""
  111. updated = False
  112. model_cache = self.pool._auditlog_model_cache
  113. for rule in self:
  114. if rule.state != 'subscribed':
  115. continue
  116. if not self.pool.get(rule.model_id.model):
  117. # ignore rules for models not loadable currently
  118. continue
  119. model_cache[rule.model_id.model] = rule.model_id.id
  120. model_model = self.env[rule.model_id.model]
  121. # CRUD
  122. # -> create
  123. check_attr = 'auditlog_ruled_create'
  124. if getattr(rule, 'log_create') \
  125. and not hasattr(model_model, check_attr):
  126. model_model._patch_method('create', self._make_create())
  127. setattr(model_model, check_attr, True)
  128. updated = True
  129. # -> read
  130. check_attr = 'auditlog_ruled_read'
  131. if getattr(rule, 'log_read') \
  132. and not hasattr(model_model, check_attr):
  133. model_model._patch_method('read', self._make_read())
  134. setattr(model_model, check_attr, True)
  135. updated = True
  136. # -> write
  137. check_attr = 'auditlog_ruled_write'
  138. if getattr(rule, 'log_write') \
  139. and not hasattr(model_model, check_attr):
  140. model_model._patch_method('write', self._make_write())
  141. setattr(model_model, check_attr, True)
  142. updated = True
  143. # -> unlink
  144. check_attr = 'auditlog_ruled_unlink'
  145. if getattr(rule, 'log_unlink') \
  146. and not hasattr(model_model, check_attr):
  147. model_model._patch_method('unlink', self._make_unlink())
  148. setattr(model_model, check_attr, True)
  149. updated = True
  150. return updated
  151. @api.multi
  152. def _revert_methods(self):
  153. """Restore original ORM methods of models defined in rules."""
  154. updated = False
  155. for rule in self:
  156. model_model = self.env[rule.model_id.model]
  157. for method in ['create', 'read', 'write', 'unlink']:
  158. if getattr(rule, 'log_%s' % method) and hasattr(
  159. getattr(model_model, method), 'origin'):
  160. model_model._revert_method(method)
  161. updated = True
  162. if updated:
  163. modules.registry.RegistryManager.signal_registry_change(
  164. self.env.cr.dbname)
  165. # Unable to find a way to declare the `create` method with the new API,
  166. # errors occurs with the `_register_hook()` BaseModel method.
  167. def create(self, cr, uid, vals, context=None):
  168. """Update the registry when a new rule is created."""
  169. res_id = super(AuditlogRule, self).create(
  170. cr, uid, vals, context=context)
  171. if self._register_hook(cr, [res_id]):
  172. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  173. return res_id
  174. # Unable to find a way to declare the `write` method with the new API,
  175. # errors occurs with the `_register_hook()` BaseModel method.
  176. def write(self, cr, uid, ids, vals, context=None):
  177. """Update the registry when existing rules are updated."""
  178. if isinstance(ids, (int, long)):
  179. ids = [ids]
  180. super(AuditlogRule, self).write(cr, uid, ids, vals, context=context)
  181. if self._register_hook(cr, ids):
  182. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  183. return True
  184. @api.multi
  185. def unlink(self):
  186. """Unsubscribe rules before removing them."""
  187. self.unsubscribe()
  188. return super(AuditlogRule, self).unlink()
  189. def _make_create(self):
  190. """Instanciate a create method that log its calls."""
  191. @api.model
  192. @api.returns('self', lambda value: value.id)
  193. def create(self, vals, **kwargs):
  194. self = self.with_context(auditlog_disabled=True)
  195. rule_model = self.env['auditlog.rule']
  196. new_record = create.origin(self, vals, **kwargs)
  197. new_values = dict(
  198. (d['id'], d) for d in new_record.sudo()
  199. .with_context(prefetch_fields=False).read(list(self._fields)))
  200. rule_model.sudo().create_logs(
  201. self.env.uid, self._name, new_record.ids,
  202. 'create', None, new_values)
  203. return new_record
  204. return create
  205. def _make_read(self):
  206. """Instanciate a read method that log its calls."""
  207. def read(self, *args, **kwargs):
  208. result = read.origin(self, *args, **kwargs)
  209. # Sometimes the result is not a list but a dictionary
  210. # Also, we can not modify the current result as it will break calls
  211. result2 = result
  212. if not isinstance(result2, list):
  213. result2 = [result]
  214. read_values = dict((d['id'], d) for d in result2)
  215. # Old API
  216. if args and isinstance(args[0], sql_db.Cursor):
  217. cr, uid, ids = args[0], args[1], args[2]
  218. if isinstance(ids, (int, long)):
  219. ids = [ids]
  220. # If the call came from auditlog itself, skip logging:
  221. # avoid logs on `read` produced by auditlog during internal
  222. # processing: read data of relevant records, 'ir.model',
  223. # 'ir.model.fields'... (no interest in logging such operations)
  224. if kwargs.get('context', {}).get('auditlog_disabled'):
  225. return result
  226. env = api.Environment(cr, uid, {'auditlog_disabled': True})
  227. rule_model = env['auditlog.rule']
  228. rule_model.sudo().create_logs(
  229. env.uid, self._name, ids,
  230. 'read', read_values)
  231. # New API
  232. else:
  233. # If the call came from auditlog itself, skip logging:
  234. # avoid logs on `read` produced by auditlog during internal
  235. # processing: read data of relevant records, 'ir.model',
  236. # 'ir.model.fields'... (no interest in logging such operations)
  237. if self.env.context.get('auditlog_disabled'):
  238. return result
  239. self = self.with_context(auditlog_disabled=True)
  240. rule_model = self.env['auditlog.rule']
  241. rule_model.sudo().create_logs(
  242. self.env.uid, self._name, self.ids,
  243. 'read', read_values)
  244. return result
  245. return read
  246. def _make_write(self):
  247. """Instanciate a write method that log its calls."""
  248. @api.multi
  249. def write(self, vals, **kwargs):
  250. self = self.with_context(auditlog_disabled=True)
  251. rule_model = self.env['auditlog.rule']
  252. old_values = dict(
  253. (d['id'], d) for d in self.sudo()
  254. .with_context(prefetch_fields=False).read(list(self._fields)))
  255. result = write.origin(self, vals, **kwargs)
  256. new_values = dict(
  257. (d['id'], d) for d in self.sudo()
  258. .with_context(prefetch_fields=False).read(list(self._fields)))
  259. rule_model.sudo().create_logs(
  260. self.env.uid, self._name, self.ids,
  261. 'write', old_values, new_values)
  262. return result
  263. return write
  264. def _make_unlink(self):
  265. """Instanciate an unlink method that log its calls."""
  266. @api.multi
  267. def unlink(self, **kwargs):
  268. self = self.with_context(auditlog_disabled=True)
  269. rule_model = self.env['auditlog.rule']
  270. old_values = dict(
  271. (d['id'], d) for d in self.sudo()
  272. .with_context(prefetch_fields=False).read(list(self._fields)))
  273. rule_model.sudo().create_logs(
  274. self.env.uid, self._name, self.ids, 'unlink', old_values)
  275. return unlink.origin(self, **kwargs)
  276. return unlink
  277. def create_logs(self, uid, res_model, res_ids, method,
  278. old_values=None, new_values=None,
  279. additional_log_values=None):
  280. """Create logs. `old_values` and `new_values` are dictionnaries, e.g:
  281. {RES_ID: {'FIELD': VALUE, ...}}
  282. """
  283. if old_values is None:
  284. old_values = EMPTY_DICT
  285. if new_values is None:
  286. new_values = EMPTY_DICT
  287. log_model = self.env['auditlog.log']
  288. http_request_model = self.env['auditlog.http.request']
  289. http_session_model = self.env['auditlog.http.session']
  290. for res_id in res_ids:
  291. model_model = self.env[res_model]
  292. name = model_model.browse(res_id).name_get()
  293. res_name = name and name[0] and name[0][1]
  294. vals = {
  295. 'name': res_name,
  296. 'model_id': self.pool._auditlog_model_cache[res_model],
  297. 'res_id': res_id,
  298. 'method': method,
  299. 'user_id': uid,
  300. 'http_request_id': http_request_model.current_http_request(),
  301. 'http_session_id': http_session_model.current_http_session(),
  302. }
  303. vals.update(additional_log_values or {})
  304. log = log_model.create(vals)
  305. diff = DictDiffer(
  306. new_values.get(res_id, EMPTY_DICT),
  307. old_values.get(res_id, EMPTY_DICT))
  308. if method is 'create':
  309. self._create_log_line_on_create(log, diff.added(), new_values)
  310. elif method is 'read':
  311. self._create_log_line_on_read(
  312. log, old_values.get(res_id, EMPTY_DICT).keys(), old_values)
  313. elif method is 'write':
  314. self._create_log_line_on_write(
  315. log, diff.changed(), old_values, new_values)
  316. def _get_field(self, model, field_name):
  317. cache = self.pool._auditlog_field_cache
  318. if field_name not in cache.get(model.model, {}):
  319. cache.setdefault(model.model, {})
  320. # - we use 'search()' then 'read()' instead of the 'search_read()'
  321. # to take advantage of the 'classic_write' loading
  322. # - search the field in the current model and those it inherits
  323. field_model = self.env['ir.model.fields']
  324. all_model_ids = [model.id]
  325. all_model_ids.extend(model.inherited_model_ids.ids)
  326. field = field_model.search(
  327. [('model_id', 'in', all_model_ids), ('name', '=', field_name)])
  328. # The field can be a dummy one, like 'in_group_X' on 'res.users'
  329. # As such we can't log it (field_id is required to create a log)
  330. if not field:
  331. cache[model.model][field_name] = False
  332. else:
  333. field_data = field.read(load='_classic_write')[0]
  334. cache[model.model][field_name] = field_data
  335. return cache[model.model][field_name]
  336. def _create_log_line_on_read(
  337. self, log, fields_list, read_values):
  338. """Log field filled on a 'read' operation."""
  339. log_line_model = self.env['auditlog.log.line']
  340. for field_name in fields_list:
  341. if field_name in FIELDS_BLACKLIST:
  342. continue
  343. field = self._get_field(log.model_id, field_name)
  344. # not all fields have an ir.models.field entry (ie. related fields)
  345. if field:
  346. log_vals = self._prepare_log_line_vals_on_read(
  347. log, field, read_values)
  348. log_line_model.create(log_vals)
  349. def _prepare_log_line_vals_on_read(self, log, field, read_values):
  350. """Prepare the dictionary of values used to create a log line on a
  351. 'read' operation.
  352. """
  353. vals = {
  354. 'field_id': field['id'],
  355. 'log_id': log.id,
  356. 'old_value': read_values[log.res_id][field['name']],
  357. 'old_value_text': read_values[log.res_id][field['name']],
  358. 'new_value': False,
  359. 'new_value_text': False,
  360. }
  361. if field['relation'] and '2many' in field['ttype']:
  362. old_value_text = self.env[field['relation']].browse(
  363. vals['old_value']).name_get()
  364. vals['old_value_text'] = old_value_text
  365. return vals
  366. def _create_log_line_on_write(
  367. self, log, fields_list, old_values, new_values):
  368. """Log field updated on a 'write' operation."""
  369. log_line_model = self.env['auditlog.log.line']
  370. for field_name in fields_list:
  371. if field_name in FIELDS_BLACKLIST:
  372. continue
  373. field = self._get_field(log.model_id, field_name)
  374. # not all fields have an ir.models.field entry (ie. related fields)
  375. if field:
  376. log_vals = self._prepare_log_line_vals_on_write(
  377. log, field, old_values, new_values)
  378. log_line_model.create(log_vals)
  379. def _prepare_log_line_vals_on_write(
  380. self, log, field, old_values, new_values):
  381. """Prepare the dictionary of values used to create a log line on a
  382. 'write' operation.
  383. """
  384. vals = {
  385. 'field_id': field['id'],
  386. 'log_id': log.id,
  387. 'old_value': old_values[log.res_id][field['name']],
  388. 'old_value_text': old_values[log.res_id][field['name']],
  389. 'new_value': new_values[log.res_id][field['name']],
  390. 'new_value_text': new_values[log.res_id][field['name']],
  391. }
  392. # for *2many fields, log the name_get
  393. if field['relation'] and '2many' in field['ttype']:
  394. # Filter IDs to prevent a 'name_get()' call on deleted resources
  395. existing_ids = self.env[field['relation']]._search(
  396. [('id', 'in', vals['old_value'])])
  397. old_value_text = []
  398. if existing_ids:
  399. existing_values = self.env[field['relation']].browse(
  400. existing_ids).name_get()
  401. old_value_text.extend(existing_values)
  402. # Deleted resources will have a 'DELETED' text representation
  403. deleted_ids = set(vals['old_value']) - set(existing_ids)
  404. for deleted_id in deleted_ids:
  405. old_value_text.append((deleted_id, 'DELETED'))
  406. vals['old_value_text'] = old_value_text
  407. new_value_text = self.env[field['relation']].browse(
  408. vals['new_value']).name_get()
  409. vals['new_value_text'] = new_value_text
  410. return vals
  411. def _create_log_line_on_create(
  412. self, log, fields_list, new_values):
  413. """Log field filled on a 'create' operation."""
  414. log_line_model = self.env['auditlog.log.line']
  415. for field_name in fields_list:
  416. if field_name in FIELDS_BLACKLIST:
  417. continue
  418. field = self._get_field(log.model_id, field_name)
  419. # not all fields have an ir.models.field entry (ie. related fields)
  420. if field:
  421. log_vals = self._prepare_log_line_vals_on_create(
  422. log, field, new_values)
  423. log_line_model.create(log_vals)
  424. def _prepare_log_line_vals_on_create(self, log, field, new_values):
  425. """Prepare the dictionary of values used to create a log line on a
  426. 'create' operation.
  427. """
  428. vals = {
  429. 'field_id': field['id'],
  430. 'log_id': log.id,
  431. 'old_value': False,
  432. 'old_value_text': False,
  433. 'new_value': new_values[log.res_id][field['name']],
  434. 'new_value_text': new_values[log.res_id][field['name']],
  435. }
  436. if field['relation'] and '2many' in field['ttype']:
  437. new_value_text = self.env[field['relation']].browse(
  438. vals['new_value']).name_get()
  439. vals['new_value_text'] = new_value_text
  440. return vals
  441. @api.multi
  442. def subscribe(self):
  443. """Subscribe Rule for auditing changes on model and apply shortcut
  444. to view logs on that model.
  445. """
  446. act_window_model = self.env['ir.actions.act_window']
  447. model_data_model = self.env['ir.model.data']
  448. for rule in self:
  449. # Create a shortcut to view logs
  450. domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
  451. rule.model_id.id)
  452. vals = {
  453. 'name': _(u"View logs"),
  454. 'res_model': 'auditlog.log',
  455. 'src_model': rule.model_id.model,
  456. 'domain': domain,
  457. }
  458. act_window = act_window_model.sudo().create(vals)
  459. rule.write({'state': 'subscribed', 'action_id': act_window.id})
  460. keyword = 'client_action_relate'
  461. value = 'ir.actions.act_window,%s' % act_window.id
  462. model_data_model.sudo().ir_set(
  463. 'action', keyword, 'View_log_' + rule.model_id.model,
  464. [rule.model_id.model], value, replace=True,
  465. isobject=True, xml_id=False)
  466. return True
  467. @api.multi
  468. def unsubscribe(self):
  469. """Unsubscribe Auditing Rule on model."""
  470. act_window_model = self.env['ir.actions.act_window']
  471. ir_values_model = self.env['ir.values']
  472. # Revert patched methods
  473. self._revert_methods()
  474. for rule in self:
  475. # Remove the shortcut to view logs
  476. act_window = act_window_model.search(
  477. [('name', '=', 'View Log'),
  478. ('res_model', '=', 'auditlog.log'),
  479. ('src_model', '=', rule.model_id.model)])
  480. if act_window:
  481. value = 'ir.actions.act_window,%s' % act_window.id
  482. act_window.unlink()
  483. ir_value = ir_values_model.search(
  484. [('model', '=', rule.model_id.model),
  485. ('value', '=', value)])
  486. if ir_value:
  487. ir_value.unlink()
  488. self.write({'state': 'draft'})
  489. return True