LogableBehavior.php 23 KB

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