LogableBehavior.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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 $_defaultConfig = [
  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' => [],
  80. 'ignore' => [],
  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 = []) {
  99. $config += (array)Configure::read('Logable');
  100. $this->settings[$Model->alias] = $config + $this->_defaultConfig;
  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 = []) {
  143. $defaults = [
  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' => [],
  149. $this->settings[$Model->alias]['foreignKey'] => null,
  150. 'fields' => [],
  151. 'limit' => 50,
  152. ];
  153. $params += $defaults;
  154. $options = ['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 [];
  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 = []) {
  192. if (!$this->UserModel) {
  193. return [];
  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. $user = $this->UserModel->find('first', ['recursive' => -1, 'conditions' => [$this->UserModel->primaryKey => $userId]]);
  201. $username = $user[$this->UserModel->alias][$this->UserModel->displayField];
  202. }
  203. $fields = [];
  204. if (isset($params['fields'])) {
  205. if (is_array($params['fields'])) {
  206. $fields = $params['fields'];
  207. } else {
  208. $fields = [$params['fields']];
  209. }
  210. }
  211. $conditions = [$this->settings[$Model->alias]['userKey'] => $userId];
  212. if (isset($params[$this->settings[$Model->alias]['classField']])) {
  213. $conditions[$this->settings[$Model->alias]['classField']] = $params[$this->settings[$Model->alias]['classField']];
  214. }
  215. $order = [$this->Log->alias . '.id' => 'DESC'];
  216. if (isset($params['order'])) {
  217. $order = $params['order'];
  218. }
  219. $data = $this->Log->find('all', [
  220. 'conditions' => $conditions,
  221. 'recursive' => -1,
  222. 'fields' => $fields,
  223. 'order' => $order
  224. ]);
  225. if (!isset($params['events']) || (isset($params['events']) && $params['events'] == false)) {
  226. return $data;
  227. }
  228. $result = [];
  229. foreach ($data as $key => $row) {
  230. $one = $row[$this->Log->alias];
  231. $result[$key][$this->Log->alias]['id'] = $one['id'];
  232. $result[$key][$this->Log->alias]['event'] = $username;
  233. // have all the detail models and change as list :
  234. if (isset($one[$this->settings[$Model->alias]['classField']]) && isset($one['action']) && isset($one['change']) && isset($one[$this->
  235. settings[$Model->alias]['foreignKey']])) {
  236. if ($one['action'] === 'edit') {
  237. $result[$key][$this->Log->alias]['event'] .= ' edited ' . $one['change'] . ' of ' . strtolower($one[$this->settings[$Model->alias]['classField']]) .
  238. '(id ' . $one[$this->settings[$Model->alias]['foreignKey']] . ')';
  239. } elseif ($one['action'] === 'add') {
  240. $result[$key][$this->Log->alias]['event'] .= ' added a ' . strtolower($one[$this->settings[$Model->alias]['classField']]) . '(id ' . $one[$this->
  241. settings[$Model->alias]['foreignKey']] . ')';
  242. } elseif ($one['action'] === 'delete') {
  243. $result[$key][$this->Log->alias]['event'] .= ' deleted the ' . strtolower($one[$this->settings[$Model->alias]['classField']]) . '(id ' . $one[$this->
  244. settings[$Model->alias]['foreignKey']] . ')';
  245. }
  246. } elseif (isset($one[$this->settings[$Model->alias]['classField']]) && isset($one['action']) && isset($one[$this->settings[$Model->alias]['foreignKey']])) { // have model,foreign_id and action
  247. if ($one['action'] === 'edit') {
  248. $result[$key][$this->Log->alias]['event'] .= ' edited ' . strtolower($one[$this->settings[$Model->alias]['classField']]) . '(id ' . $one[$this->
  249. settings[$Model->alias]['foreignKey']] . ')';
  250. } elseif ($one['action'] === 'add') {
  251. $result[$key][$this->Log->alias]['event'] .= ' added a ' . strtolower($one[$this->settings[$Model->alias]['classField']]) . '(id ' . $one[$this->
  252. settings[$Model->alias]['foreignKey']] . ')';
  253. } elseif ($one['action'] === 'delete') {
  254. $result[$key][$this->Log->alias]['event'] .= ' deleted the ' . strtolower($one[$this->settings[$Model->alias]['classField']]) . '(id ' . $one[$this->
  255. settings[$Model->alias]['foreignKey']] . ')';
  256. }
  257. } else { // only description field exist
  258. $result[$key][$this->Log->alias]['event'] = $one['description'];
  259. }
  260. }
  261. return $result;
  262. }
  263. /**
  264. * Use this to supply a model with the data of the logged in User.
  265. * Intended to be called in AppController::beforeFilter like this :
  266. *
  267. * if ($this->{$this->modelClass}->Behaviors->loaded('Logable')) {
  268. * $this->{$this->modelClass}->setUserData($activeUser);/
  269. * }
  270. *
  271. * The $userData array is expected to look like the result of a
  272. * User::find(array('id'=>123));
  273. *
  274. * @param Model $Model
  275. * @param array $userData
  276. * @return void
  277. */
  278. public function setUserData(Model $Model, $userData = null) {
  279. if ($userData === null && isset($Model->Session)) {
  280. $userData = (array)$Model->Session->read('Auth');
  281. } elseif ($userData === null && class_exists('CakeSession')) {
  282. $userData = (array)CakeSession::read('Auth');
  283. }
  284. if ($userData !== null) {
  285. $this->user = $userData;
  286. }
  287. }
  288. /**
  289. * Used for logging custom actions that arent crud, like login or download.
  290. *
  291. * @example $this->Boat->customLog('ship', 66, array('title' => 'Titanic heads out'));
  292. * @param Model $Model
  293. * @param string $action name of action that is taking place (dont use the crud ones)
  294. * @param int $id id of the logged item (ie foreign_id in logs table)
  295. * @param array $logData optional other values for your logs table
  296. * @return mixed Success
  297. */
  298. public function customLog(Model $Model, $action, $id = null, $logData = []) {
  299. if ($id === null) {
  300. $id = $Model->id;
  301. }
  302. if ($this->Log->hasField($this->settings[$Model->alias]['foreignKey']) && is_numeric($id)) {
  303. $logData[$this->settings[$Model->alias]['foreignKey']] = $id;
  304. }
  305. $title = null;
  306. if (isset($logData['title'])) {
  307. $title = $logData['title'];
  308. unset($logData['title']);
  309. }
  310. $logData['action'] = $action;
  311. return $this->_saveLog($Model, $logData, $title);
  312. }
  313. /**
  314. * LogableBehavior::clearUserData()
  315. *
  316. * @param Model $Model
  317. * @return void
  318. */
  319. public function clearUserData(Model $Model) {
  320. $this->user = null;
  321. }
  322. /**
  323. * LogableBehavior::setUserIp()
  324. *
  325. * @param Model $Model
  326. * @param mixed $userIP
  327. * @return void
  328. */
  329. public function setUserIp(Model $Model, $userIP = null) {
  330. if ($userIP === null) {
  331. $userIP = Utility::getClientIp();
  332. }
  333. $this->userIP = $userIP;
  334. }
  335. /**
  336. * LogableBehavior::beforeDelete()
  337. *
  338. * @param Model $Model
  339. * @param bool $cascade
  340. * @return bool Success
  341. */
  342. public function beforeDelete(Model $Model, $cascade = true) {
  343. $this->setUserData($Model);
  344. if (!$this->settings[$Model->alias]['enabled']) {
  345. return true;
  346. }
  347. if (isset($this->settings[$Model->alias]['skip']['delete']) && $this->settings[$Model->alias]['skip']['delete']) {
  348. return true;
  349. }
  350. $Model->recursive = -1;
  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 = $Model->field($Model->displayField)) {
  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. }