LogableBehavior.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. <?php
  2. App::uses('CakeSession', 'Model/Datasource');
  3. App::uses('ModelBehavior', 'Model');
  4. App::uses('Utility', 'Utility');
  5. if (!defined('CLASS_USER')) {
  6. define('CLASS_USER', 'User');
  7. }
  8. /**
  9. * Logs saves and deletes of any model
  10. *
  11. * Requires the following to work as intended :
  12. *
  13. * - "Log" model ( empty but for a order variable [created DESC]
  14. * - "logs" table with these fields required :
  15. * - id [int]
  16. * - title [string] : automagically filled with the display field of the model that was modified.
  17. * - created [date/datetime] : filled by cake in normal way
  18. *
  19. * - actsAs = array("Tools.Logable"); on models that should be logged
  20. *
  21. * Optional extra table fields for the "logs" table :
  22. *
  23. * - "description" [string] : Fill with a descriptive text of what, who and to which model/row :
  24. * "Contact "John Smith"(34) added by User "Administrator"(1).
  25. *
  26. * or if u want more detail, add any combination of the following :
  27. *
  28. * - "" [string] : automagically filled with the class name of the model that generated the activity.
  29. * - "foreign_id" [int] : automagically filled with the primary key of the model that was modified.
  30. * - "action" [string] : automagically filled with what action is made (add/edit/delete)
  31. * - "user_id" [int] : populated with the supplied user info. (May be renamed. See bellow.)
  32. * - "change" [string] : depending on setting either :
  33. * [name (alek) => (Alek), age (28) => (29)] or [name, age]
  34. *
  35. * - "version_id" [int] : cooperates with RevisionBehavior to link the the shadow table (thus linking to old data)
  36. *
  37. * Remember that Logable behavior needs to be added after RevisionBehavior. In fact, just put it last to be safe.
  38. *
  39. * Optionally register what user was responsable for the activity :
  40. *
  41. * - Supply configuration only if defaults are wrong. Example given with defaults :
  42. *
  43. * public $actsAs = array('Tools.Logable' => array('userModel' => 'User', 'userKey' => 'user_id'));
  44. *
  45. * - In AppController (or single controller if only needed once) add these lines to beforeFilter :
  46. *
  47. * if (count($this->uses) && $this->{$this->modelClass}->Behaviors->loaded('Logable')) {
  48. * $this->{$this->modelClass}->setUserData($this->activeUser);
  49. * }
  50. *
  51. * Where "$activeUser" should be an array in the standard format for the User model used :
  52. *
  53. * $activeUser = array( $UserModel->alias => array( $UserModel->primaryKey => 123, $UserModel->displayField => 'Alexander'));
  54. * // any other key is just ignored by this behaviour.
  55. *
  56. * @author Alexander Morland (alexander#maritimecolours.no)
  57. * @co-author Eskil Mjelva Saatvedt
  58. * @co-author Ronny Vindenes
  59. * @co-author Carl Erik Fyllingen
  60. * @contributor Miha
  61. * @category Behavior
  62. * @version 2.2
  63. * @modified 3.june 2009 by Miha
  64. * @modified 2011-11-17 ms (mark scherer) cake2.0 ready
  65. *
  66. */
  67. class LogableBehavior extends ModelBehavior {
  68. public $user = null;
  69. public $old = null;
  70. public $UserModel = null;
  71. protected $_defaults = array(
  72. 'enabled' => true,
  73. 'on' => 'save', // On validate/save
  74. 'userModel' => CLASS_USER,
  75. 'logModel' => 'Tools.Log',
  76. 'userKey' => 'user_id',
  77. 'change' => 'list',
  78. 'descriptionIds' => true,
  79. 'skip' => array(),
  80. 'ignore' => array(),
  81. 'classField' => 'model',
  82. 'foreignKey' => 'foreign_id',
  83. 'autoRelation' => false, // Attach relation to the model (hasMany Log)
  84. );
  85. /**
  86. * Config options are :
  87. * - userModel : 'User'. Class name of the user model you want to use (User by default), if you want to save User in log
  88. * - userKey : 'user_id'. The field for saving the user to (user_id by default).
  89. * - change : 'list' > [name, age]. Set to 'full' for [name (alek) => (Alek), age (28) => (29)]
  90. * - descriptionIds : TRUE. Set to false to not include model id and user id in the title field
  91. * - skip: array(). String array of actions to not log.
  92. * - ignore: array(). Fields to ignore. The primary key will always be ignored.
  93. *
  94. * @param Model $Model
  95. * @param array $config
  96. * @return void
  97. */
  98. public function setup(Model $Model, $config = array()) {
  99. $config += (array)Configure::read('Logable');
  100. $this->settings[$Model->alias] = $config + $this->_defaults;
  101. $this->settings[$Model->alias]['ignore'][] = $Model->primaryKey;
  102. $this->Log = ClassRegistry::init($this->settings[$Model->alias]['logModel']);
  103. if ($this->settings[$Model->alias]['userModel'] !== $Model->alias) {
  104. $this->UserModel = ClassRegistry::init($this->settings[$Model->alias]['userModel']);
  105. } else {
  106. $this->UserModel = $Model;
  107. }
  108. }
  109. /**
  110. * LogableBehavior::enableLog()
  111. *
  112. * @param Model $Model
  113. * @param bool $enable
  114. * @return bool Current enabled status
  115. */
  116. public function enableLog(Model $Model, $enable = null) {
  117. if ($enable !== null) {
  118. $this->settings[$Model->alias]['enabled'] = $enable;
  119. }
  120. return $this->settings[$Model->alias]['enabled'];
  121. }
  122. /**
  123. * Useful for getting logs for a model, takes params to narrow find.
  124. * This method can actually also be used to find logs for all models or
  125. * even another model. Using no params will return all activities for
  126. * the models it is called from.
  127. *
  128. * Possible params :
  129. * 'model' : mixed (null) String with className, null to get current or false to get everything
  130. * 'action' : string (null) String with action (add/edit/delete), null gets all
  131. * 'order' : string ('created DESC') String with custom order
  132. * 'conditions : array (array()) Add custom conditions
  133. * 'foreign_id' : int (null) Add a int
  134. *
  135. * (remember to use your own user key if you're not using 'user_id')
  136. * 'user_id' : int (null) Defaults to all users, supply id if you want for only one User
  137. *
  138. * @param Model $Model
  139. * @param array $params
  140. * @return array
  141. */
  142. public function findLog(Model $Model, $params = array()) {
  143. $defaults = array(
  144. $this->settings[$Model->alias]['classField'] => null,
  145. 'action' => null,
  146. 'order' => $this->Log->alias . '.id DESC',
  147. $this->settings[$Model->alias]['userKey'] => null,
  148. 'conditions' => array(),
  149. $this->settings[$Model->alias]['foreignKey'] => null,
  150. 'fields' => array(),
  151. 'limit' => 50,
  152. );
  153. $params = array_merge($defaults, $params);
  154. $options = array('order' => $params['order'], 'conditions' => $params['conditions'], 'fields' => $params['fields'], 'limit' => $params['limit']);
  155. if ($params[$this->settings[$Model->alias]['classField']] === null) {
  156. $params[$this->settings[$Model->alias]['classField']] = $Model->alias;
  157. }
  158. if ($params[$this->settings[$Model->alias]['classField']]) {
  159. if ($this->Log->hasField($this->settings[$Model->alias]['classField'])) {
  160. $options['conditions'][$this->settings[$Model->alias]['classField']] = $params[$this->settings[$Model->alias]['classField']];
  161. } elseif ($this->Log->hasField('description')) {
  162. $options['conditions']['description LIKE '] = $params[$this->settings[$Model->alias]['classField']] . '%';
  163. } else {
  164. return array();
  165. }
  166. }
  167. if ($params['action'] && $this->Log->hasField('action')) {
  168. $options['conditions']['action'] = $params['action'];
  169. }
  170. if ($params[$this->settings[$Model->alias]['userKey']] && $this->UserModel && is_numeric($params[$this->settings[$Model->alias]['userKey']])) {
  171. $options['conditions'][$this->settings[$Model->alias]['userKey']] = $params[$this->settings[$Model->alias]['userKey']];
  172. }
  173. if ($params[$this->settings[$Model->alias]['foreignKey']] && is_numeric($params[$this->settings[$Model->alias]['foreignKey']])) {
  174. $options['conditions'][$this->settings[$Model->alias]['foreignKey']] = $params[$this->settings[$Model->alias]['foreignKey']];
  175. }
  176. return $this->Log->find('all', $options);
  177. }
  178. /**
  179. * Get list of actions for one user.
  180. * Params for getting (one line) activity descriptions
  181. * and/or for just one model
  182. *
  183. * @example $this->Model->findUserActions(301, array('model' => 'BookTest'));
  184. * @example $this->Model->findUserActions(301, array('events' => true));
  185. * @example $this->Model->findUserActions(301, array('fields' => array('id','model'),'model' => 'BookTest');
  186. * @param Model $Model
  187. * @param int $userId
  188. * @param array $params
  189. * @return array
  190. */
  191. public function findUserActions(Model $Model, $userId, $params = array()) {
  192. if (!$this->UserModel) {
  193. return array();
  194. }
  195. // if logged in user is asking for her own log, use the data we allready have
  196. if (isset($this->user) && isset($this->user[$this->UserModel->alias][$this->UserModel->primaryKey]) && $userId == $this->user[$this->
  197. UserModel->alias][$this->UserModel->primaryKey] && isset($this->user[$this->UserModel->alias][$this->UserModel->displayField])) {
  198. $username = $this->user[$this->UserModel->alias][$this->UserModel->displayField];
  199. } else {
  200. $this->UserModel->recursive = -1;
  201. $user = $this->UserModel->find('first', array('conditions' => array($this->UserModel->primaryKey => $userId)));
  202. $username = $user[$this->UserModel->alias][$this->UserModel->displayField];
  203. }
  204. $fields = array();
  205. if (isset($params['fields'])) {
  206. if (is_array($params['fields'])) {
  207. $fields = $params['fields'];
  208. } else {
  209. $fields = array($params['fields']);
  210. }
  211. }
  212. $conditions = array($this->settings[$Model->alias]['userKey'] => $userId);
  213. if (isset($params[$this->settings[$Model->alias]['classField']])) {
  214. $conditions[$this->settings[$Model->alias]['classField']] = $params[$this->settings[$Model->alias]['classField']];
  215. }
  216. $order = array($this->Log->alias . '.id' => 'DESC');
  217. if (isset($params['order'])) {
  218. $order = $params['order'];
  219. }
  220. $data = $this->Log->find('all', array(
  221. 'conditions' => $conditions,
  222. 'recursive' => -1,
  223. 'fields' => $fields,
  224. 'order' => $order
  225. ));
  226. if (!isset($params['events']) || (isset($params['events']) && $params['events'] == false)) {
  227. return $data;
  228. }
  229. $result = array();
  230. foreach ($data as $key => $row) {
  231. $one = $row[$this->Log->alias];
  232. $result[$key][$this->Log->alias]['id'] = $one['id'];
  233. $result[$key][$this->Log->alias]['event'] = $username;
  234. // have all the detail models and change as list :
  235. if (isset($one[$this->settings[$Model->alias]['classField']]) && isset($one['action']) && isset($one['change']) && isset($one[$this->
  236. settings[$Model->alias]['foreignKey']])) {
  237. if ($one['action'] === 'edit') {
  238. $result[$key][$this->Log->alias]['event'] .= ' edited ' . $one['change'] . ' of ' . strtolower($one[$this->settings[$Model->alias]['classField']]) .
  239. '(id ' . $one[$this->settings[$Model->alias]['foreignKey']] . ')';
  240. // ' at '.$one['created'];
  241. } elseif ($one['action'] === 'add') {
  242. $result[$key][$this->Log->alias]['event'] .= ' added a ' . strtolower($one[$this->settings[$Model->alias]['classField']]) . '(id ' . $one[$this->
  243. settings[$Model->alias]['foreignKey']] . ')';
  244. } elseif ($one['action'] === 'delete') {
  245. $result[$key][$this->Log->alias]['event'] .= ' deleted the ' . strtolower($one[$this->settings[$Model->alias]['classField']]) . '(id ' . $one[$this->
  246. settings[$Model->alias]['foreignKey']] . ')';
  247. }
  248. } elseif (isset($one[$this->settings[$Model->alias]['classField']]) && isset($one['action']) && isset($one[$this->settings[$Model->alias]['foreignKey']])) { // have model,foreign_id and action
  249. if ($one['action'] === 'edit') {
  250. $result[$key][$this->Log->alias]['event'] .= ' edited ' . strtolower($one[$this->settings[$Model->alias]['classField']]) . '(id ' . $one[$this->
  251. settings[$Model->alias]['foreignKey']] . ')';
  252. // ' at '.$one['created'];
  253. } elseif ($one['action'] === 'add') {
  254. $result[$key][$this->Log->alias]['event'] .= ' added a ' . strtolower($one[$this->settings[$Model->alias]['classField']]) . '(id ' . $one[$this->
  255. settings[$Model->alias]['foreignKey']] . ')';
  256. } elseif ($one['action'] === 'delete') {
  257. $result[$key][$this->Log->alias]['event'] .= ' deleted the ' . strtolower($one[$this->settings[$Model->alias]['classField']]) . '(id ' . $one[$this->
  258. settings[$Model->alias]['foreignKey']] . ')';
  259. }
  260. } else { // only description field exist
  261. $result[$key][$this->Log->alias]['event'] = $one['description'];
  262. }
  263. }
  264. return $result;
  265. }
  266. /**
  267. * Use this to supply a model with the data of the logged in User.
  268. * Intended to be called in AppController::beforeFilter like this :
  269. *
  270. * if ($this->{$this->modelClass}->Behaviors->loaded('Logable')) {
  271. * $this->{$this->modelClass}->setUserData($activeUser);/
  272. * }
  273. *
  274. * The $userData array is expected to look like the result of a
  275. * User::find(array('id'=>123));
  276. *
  277. * @param Model $Model
  278. * @param array $userData
  279. * @return void
  280. */
  281. public function setUserData(Model $Model, $userData = null) {
  282. if ($userData === null && isset($Model->Session)) {
  283. $userData = (array)$Model->Session->read('Auth');
  284. } elseif ($userData === null && class_exists('CakeSession')) {
  285. $userData = (array)CakeSession::read('Auth');
  286. }
  287. if ($userData !== null) {
  288. $this->user = $userData;
  289. }
  290. }
  291. /**
  292. * Used for logging custom actions that arent crud, like login or download.
  293. *
  294. * @example $this->Boat->customLog('ship', 66, array('title' => 'Titanic heads out'));
  295. * @param Model $Model
  296. * @param string $action name of action that is taking place (dont use the crud ones)
  297. * @param int $id id of the logged item (ie foreign_id in logs table)
  298. * @param array $values optional other values for your logs table
  299. * @return mixed Success
  300. */
  301. public function customLog(Model $Model, $action, $id = null, $logData = array()) {
  302. if ($id === null) {
  303. $id = $Model->id;
  304. }
  305. if ($this->Log->hasField($this->settings[$Model->alias]['foreignKey']) && is_numeric($id)) {
  306. $logData[$this->settings[$Model->alias]['foreignKey']] = $id;
  307. }
  308. $title = null;
  309. if (isset($values['title'])) {
  310. $title = $values['title'];
  311. unset($logData['title']);
  312. }
  313. $logData['action'] = $action;
  314. return $this->_saveLog($Model, $logData, $title);
  315. }
  316. /**
  317. * LogableBehavior::clearUserData()
  318. *
  319. * @param Model $Model
  320. * @return void
  321. */
  322. public function clearUserData(Model $Model) {
  323. $this->user = null;
  324. }
  325. /**
  326. * LogableBehavior::setUserIp()
  327. *
  328. * @param Model $Model
  329. * @param mixed $userIP
  330. * @return void
  331. */
  332. public function setUserIp(Model $Model, $userIP = null) {
  333. if ($userIP === null) {
  334. $userIP = Utility::getClientIp();
  335. }
  336. $this->userIP = $userIP;
  337. }
  338. public function beforeDelete(Model $Model, $cascade = true) {
  339. $this->setUserData($Model);
  340. if (!$this->settings[$Model->alias]['enabled']) {
  341. return true;
  342. }
  343. if (isset($this->settings[$Model->alias]['skip']['delete']) && $this->settings[$Model->alias]['skip']['delete']) {
  344. return true;
  345. }
  346. $Model->recursive = -1;
  347. $Model->read();
  348. return true;
  349. }
  350. public function afterDelete(Model $Model) {
  351. if (!$this->settings[$Model->alias]['enabled']) {
  352. return true;
  353. }
  354. if (isset($this->settings[$Model->alias]['skip']['delete']) && $this->settings[$Model->alias]['skip']['delete']) {
  355. return true;
  356. }
  357. $logData = array();
  358. if ($this->Log->hasField('description')) {
  359. $logData['description'] = $Model->alias;
  360. if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
  361. $logData['description'] .= ' "' . $Model->data[$Model->alias][$Model->displayField] . '"';
  362. }
  363. if ($this->settings[$Model->alias]['descriptionIds']) {
  364. $logData['description'] .= ' (' . $Model->id . ') ';
  365. }
  366. $logData['description'] .= __('deleted');
  367. }
  368. $logData['action'] = 'delete';
  369. if (!$this->_saveLog($Model, $logData)) {
  370. throw new RuntimeException('Logging failed');
  371. }
  372. }
  373. public function beforeValidate(Model $Model, $options = array()) {
  374. if (!$this->settings[$Model->alias]['enabled'] || $this->settings[$Model->alias]['on'] !== 'validate') {
  375. return true;
  376. }
  377. $this->_prepareLog($Model);
  378. return true;
  379. }
  380. public function beforeSave(Model $Model, $options = array()) {
  381. if (!$this->settings[$Model->alias]['enabled'] || $this->settings[$Model->alias]['on'] !== 'save') {
  382. return true;
  383. }
  384. $this->_prepareLog($Model);
  385. return true;
  386. }
  387. public function afterSave(Model $Model, $created, $options = array()) {
  388. if (!$this->settings[$Model->alias]['enabled']) {
  389. return true;
  390. }
  391. if (!empty($this->settings[$Model->alias]['skip']['add']) && $created) {
  392. return true;
  393. } elseif (!empty($this->settings[$Model->alias]['skip']['edit']) && !$created) {
  394. return true;
  395. }
  396. $keys = array_keys($Model->data[$Model->alias]);
  397. $diff = array_diff($keys, $this->settings[$Model->alias]['ignore']);
  398. if (count($diff) === 0 && empty($Model->logableAction)) {
  399. return false;
  400. }
  401. if ($Model->id) {
  402. $id = $Model->id;
  403. } elseif ($Model->insertId) {
  404. $id = $Model->insertId;
  405. }
  406. if ($this->Log->hasField($this->settings[$Model->alias]['foreignKey'])) {
  407. $logData[$this->settings[$Model->alias]['foreignKey']] = $id;
  408. }
  409. if ($this->Log->hasField('description')) {
  410. $logData['description'] = $Model->alias . ' ';
  411. if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
  412. $logData['description'] .= '"' . $Model->data[$Model->alias][$Model->displayField] . '" ';
  413. }
  414. if ($this->settings[$Model->alias]['descriptionIds']) {
  415. $logData['description'] .= '(' . $id . ') ';
  416. }
  417. if ($created) {
  418. $logData['description'] .= __('added');
  419. } else {
  420. $logData['description'] .= __('updated');
  421. }
  422. }
  423. if ($this->Log->hasField('action')) {
  424. if ($created) {
  425. $logData['action'] = 'add';
  426. } else {
  427. $logData['action'] = 'edit';
  428. }
  429. }
  430. if ($this->Log->hasField('change')) {
  431. $logData['change'] = '';
  432. $dbFields = array_keys($Model->schema());
  433. $changedFields = array();
  434. foreach ($Model->data[$Model->alias] as $key => $value) {
  435. if (isset($Model->data[$Model->alias][$Model->primaryKey]) && !empty($this->old) && isset($this->old[$Model->alias][$key])) {
  436. $old = $this->old[$Model->alias][$key];
  437. } else {
  438. $old = '';
  439. }
  440. if ($key !== 'modified' && !in_array($key, $this->settings[$Model->alias]['ignore']) && $value != $old && in_array($key, $dbFields)) {
  441. if ($this->settings[$Model->alias]['change'] === 'full') {
  442. $changedFields[] = $key . ' (' . $old . ') => (' . $value . ')';
  443. } elseif ($this->settings[$Model->alias]['change'] === 'serialize') {
  444. $changedFields[$key] = array('old' => $old, 'value' => $value);
  445. } else {
  446. $changedFields[] = $key;
  447. }
  448. }
  449. }
  450. $changes = count($changedFields);
  451. if (!$changes) {
  452. return true;
  453. }
  454. if ($this->settings[$Model->alias]['change'] === 'serialize') {
  455. $logData['change'] = serialize($changedFields);
  456. } else {
  457. $logData['change'] = implode(', ', $changedFields);
  458. }
  459. $logData['changes'] = $changes;
  460. }
  461. if (empty($logData)) {
  462. return true;
  463. }
  464. return $this->_saveLog($Model, $logData);
  465. }
  466. /**
  467. * LogableBehavior::settings()
  468. *
  469. * @param mixed $Model
  470. * @return array
  471. * @deprecated Directly use settings instead.
  472. */
  473. public function settings(Model $Model) {
  474. return $this->settings[$Model->alias];
  475. }
  476. /**
  477. * LogableBehavior::_prepareLog()
  478. *
  479. * @param Model $Model
  480. * @return void
  481. */
  482. protected function _prepareLog(Model $Model) {
  483. if ($this->user === null) {
  484. $this->setUserData($Model);
  485. }
  486. if ($Model->id && empty($this->old)) {
  487. $options = array('conditions' => array($Model->primaryKey => $Model->id), 'recursive' => -1);
  488. $this->old = $Model->find('first', $options);
  489. }
  490. }
  491. /**
  492. * Does the actual saving of the Log model. Also adds the special field if possible.
  493. *
  494. * If model field in table, add the Model->alias
  495. * If action field is NOT in table, remove it from dataset
  496. * If the userKey field in table, add it to dataset
  497. * If userData is supplied to model, add it to the title
  498. *
  499. * @param Model $Model
  500. * @param array $logData
  501. * @return mixed Success
  502. */
  503. protected function _saveLog(Model $Model, $logData, $title = null) {
  504. if ($title !== null) {
  505. $logData['title'] = $title;
  506. } elseif ($Model->displayField == $Model->primaryKey) {
  507. $logData['title'] = $Model->alias . ' (' . $Model->id . ')';
  508. } elseif (!empty($Model->data[$Model->alias][$Model->displayField])) {
  509. $logData['title'] = $Model->data[$Model->alias][$Model->displayField];
  510. } elseif ($Model->id && $title = $Model->field($Model->displayField)) {
  511. $logData['title'] = $title;
  512. } elseif (!empty($logData[$this->settings[$Model->alias]['foreignKey']])) {
  513. $options = array(
  514. 'conditions' => $logData[$this->settings[$Model->alias]['foreignKey']],
  515. 'recursive' => -1
  516. );
  517. $record = $Model->find('first', $options);
  518. if ($record) {
  519. $logData['title'] = $record[$Model->alias][$Model->displayField];
  520. }
  521. }
  522. if ($this->Log->hasField($this->settings[$Model->alias]['classField'])) {
  523. $logData[$this->settings[$Model->alias]['classField']] = $Model->name;
  524. }
  525. if ($this->Log->hasField($this->settings[$Model->alias]['foreignKey']) && !isset($logData[$this->settings[$Model->alias]['foreignKey']])) {
  526. if ($Model->id) {
  527. $logData[$this->settings[$Model->alias]['foreignKey']] = $Model->id;
  528. } elseif ($Model->insertId) {
  529. $logData[$this->settings[$Model->alias]['foreignKey']] = $Model->insertId;
  530. }
  531. }
  532. if (!$this->Log->hasField('action')) {
  533. unset($logData['action']);
  534. } elseif (isset($Model->logableAction) && !empty($Model->logableAction)) {
  535. $logData['action'] = implode(',', $Model->logableAction);
  536. }
  537. if ($this->Log->hasField('version_id') && isset($Model->versionId)) {
  538. $logData['version_id'] = $Model->versionId;
  539. }
  540. if ($this->Log->hasField('ip') && $this->userIP) {
  541. $logData['ip'] = $this->userIP;
  542. }
  543. if ($this->Log->hasField($this->settings[$Model->alias]['userKey']) && $this->user && isset($this->user[$this->UserModel->alias])) {
  544. $logData[$this->settings[$Model->alias]['userKey']] = $this->user[$this->UserModel->alias][$this->UserModel->primaryKey];
  545. }
  546. if ($this->Log->hasField('description')) {
  547. if (empty($logData['description'])) {
  548. $logData['description'] = __('Custom action');
  549. }
  550. if ($this->user && $this->UserModel && isset($this->user[$this->UserModel->alias])) {
  551. $logData['description'] .= ' ' . __('by') . ' ' . $this->settings[$Model->alias]['userModel'] . ' "' . $this->user[$this->UserModel->alias][$this->UserModel->displayField] . '"';
  552. if ($this->settings[$Model->alias]['descriptionIds']) {
  553. $logData['description'] .= ' (' . $this->user[$this->UserModel->alias][$this->UserModel->primaryKey] . ')';
  554. }
  555. } else {
  556. // UserModel is active, but the data hasnt been set. Assume system action.
  557. $logData['description'] .= ' ' . __('by System');
  558. }
  559. $logData['description'] .= '.';
  560. }
  561. if (empty($logData['title'])) {
  562. // Fallback in case the title is null - add the action + ed
  563. $logData['title'] = $Model->alias . ' ' . $logData['action'] . 'ed';
  564. }
  565. $this->Log->create($logData);
  566. return $this->Log->save(null, array('validate' => false, 'callbacks' => false));
  567. }
  568. }