LogableBehavior.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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 = 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->_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 = 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. } 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 $values optional other values for your logs table
  297. * @return mixed Success
  298. */
  299. public function customLog(Model $Model, $action, $id = null, $logData = array()) {
  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($values['title'])) {
  308. $title = $values['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->recursive = -1;
  352. $Model->read();
  353. return true;
  354. }
  355. /**
  356. * LogableBehavior::afterDelete()
  357. *
  358. * @param Model $Model
  359. * @return bool
  360. */
  361. public function afterDelete(Model $Model) {
  362. if (!$this->settings[$Model->alias]['enabled']) {
  363. return true;
  364. }
  365. if (isset($this->settings[$Model->alias]['skip']['delete']) && $this->settings[$Model->alias]['skip']['delete']) {
  366. return true;
  367. }
  368. $logData = array();
  369. if ($this->Log->hasField('description')) {
  370. $logData['description'] = $Model->alias;
  371. if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
  372. $logData['description'] .= ' "' . $Model->data[$Model->alias][$Model->displayField] . '"';
  373. }
  374. if ($this->settings[$Model->alias]['descriptionIds']) {
  375. $logData['description'] .= ' (' . $Model->id . ') ';
  376. }
  377. $logData['description'] .= __('deleted');
  378. }
  379. $logData['action'] = 'delete';
  380. if (!$this->_saveLog($Model, $logData)) {
  381. throw new RuntimeException('Logging failed');
  382. }
  383. }
  384. /**
  385. * LogableBehavior::beforeValidate()
  386. *
  387. * @param Model $Model
  388. * @param array $options
  389. * @return bool
  390. */
  391. public function beforeValidate(Model $Model, $options = array()) {
  392. if (!$this->settings[$Model->alias]['enabled'] || $this->settings[$Model->alias]['on'] !== 'validate') {
  393. return true;
  394. }
  395. $this->_prepareLog($Model);
  396. return true;
  397. }
  398. /**
  399. * LogableBehavior::beforeSave()
  400. *
  401. * @param Model $Model
  402. * @param array $options
  403. * @return bool
  404. */
  405. public function beforeSave(Model $Model, $options = array()) {
  406. if (!$this->settings[$Model->alias]['enabled'] || $this->settings[$Model->alias]['on'] !== 'save') {
  407. return true;
  408. }
  409. $this->_prepareLog($Model);
  410. return true;
  411. }
  412. /**
  413. * LogableBehavior::afterSave()
  414. *
  415. * @param Model $Model
  416. * @param bool $created
  417. * @param array $options
  418. * @return bool
  419. */
  420. public function afterSave(Model $Model, $created, $options = array()) {
  421. if (!$this->settings[$Model->alias]['enabled']) {
  422. return true;
  423. }
  424. if (!empty($this->settings[$Model->alias]['skip']['add']) && $created) {
  425. return true;
  426. } elseif (!empty($this->settings[$Model->alias]['skip']['edit']) && !$created) {
  427. return true;
  428. }
  429. $keys = array_keys($Model->data[$Model->alias]);
  430. $diff = array_diff($keys, $this->settings[$Model->alias]['ignore']);
  431. if (count($diff) === 0 && empty($Model->logableAction)) {
  432. return false;
  433. }
  434. $logData = array();
  435. if ($Model->id) {
  436. $id = $Model->id;
  437. } elseif ($Model->insertId) {
  438. $id = $Model->insertId;
  439. }
  440. if (!empty($id) && $this->Log->hasField($this->settings[$Model->alias]['foreignKey'])) {
  441. $logData[$this->settings[$Model->alias]['foreignKey']] = $id;
  442. }
  443. if ($this->Log->hasField('description')) {
  444. $logData['description'] = $Model->alias . ' ';
  445. if (isset($Model->data[$Model->alias][$Model->displayField]) && $Model->displayField != $Model->primaryKey) {
  446. $logData['description'] .= '"' . $Model->data[$Model->alias][$Model->displayField] . '" ';
  447. }
  448. if (!empty($id) && $this->settings[$Model->alias]['descriptionIds']) {
  449. $logData['description'] .= '(' . $id . ') ';
  450. }
  451. if ($created) {
  452. $logData['description'] .= __('added');
  453. } else {
  454. $logData['description'] .= __('updated');
  455. }
  456. }
  457. if ($this->Log->hasField('action')) {
  458. if ($created) {
  459. $logData['action'] = 'add';
  460. } else {
  461. $logData['action'] = 'edit';
  462. }
  463. }
  464. if ($this->Log->hasField('change')) {
  465. $logData['change'] = '';
  466. $dbFields = array_keys($Model->schema());
  467. $changedFields = array();
  468. foreach ($Model->data[$Model->alias] as $key => $value) {
  469. if (isset($Model->data[$Model->alias][$Model->primaryKey]) && !empty($this->old) && isset($this->old[$Model->alias][$key])) {
  470. $old = $this->old[$Model->alias][$key];
  471. } else {
  472. $old = '';
  473. }
  474. if ($key !== 'modified' && !in_array($key, $this->settings[$Model->alias]['ignore']) && $value != $old && in_array($key, $dbFields)) {
  475. if ($this->settings[$Model->alias]['change'] === 'full') {
  476. $changedFields[] = $key . ' (' . $old . ') => (' . $value . ')';
  477. } elseif ($this->settings[$Model->alias]['change'] === 'serialize') {
  478. $changedFields[$key] = array('old' => $old, 'value' => $value);
  479. } else {
  480. $changedFields[] = $key;
  481. }
  482. }
  483. }
  484. $changes = count($changedFields);
  485. if (!$changes) {
  486. return true;
  487. }
  488. if ($this->settings[$Model->alias]['change'] === 'serialize') {
  489. $logData['change'] = serialize($changedFields);
  490. } else {
  491. $logData['change'] = implode(', ', $changedFields);
  492. }
  493. $logData['changes'] = $changes;
  494. }
  495. if (empty($logData)) {
  496. return true;
  497. }
  498. return $this->_saveLog($Model, $logData);
  499. }
  500. /**
  501. * LogableBehavior::settings()
  502. *
  503. * @param mixed $Model
  504. * @return array
  505. * @deprecated Directly use settings instead.
  506. */
  507. public function settings(Model $Model) {
  508. return $this->settings[$Model->alias];
  509. }
  510. /**
  511. * LogableBehavior::_prepareLog()
  512. *
  513. * @param Model $Model
  514. * @return void
  515. */
  516. protected function _prepareLog(Model $Model) {
  517. if ($this->user === null) {
  518. $this->setUserData($Model);
  519. }
  520. if ($Model->id && empty($this->old)) {
  521. $options = array('conditions' => array($Model->primaryKey => $Model->id), 'recursive' => -1);
  522. $this->old = $Model->find('first', $options);
  523. }
  524. }
  525. /**
  526. * Does the actual saving of the Log model. Also adds the special field if possible.
  527. *
  528. * If model field in table, add the Model->alias
  529. * If action field is NOT in table, remove it from dataset
  530. * If the userKey field in table, add it to dataset
  531. * If userData is supplied to model, add it to the title
  532. *
  533. * @param Model $Model
  534. * @param array $logData
  535. * @return mixed Success
  536. */
  537. protected function _saveLog(Model $Model, $logData, $title = null) {
  538. if ($title !== null) {
  539. $logData['title'] = $title;
  540. } elseif ($Model->displayField == $Model->primaryKey) {
  541. $logData['title'] = $Model->alias . ' (' . $Model->id . ')';
  542. } elseif (!empty($Model->data[$Model->alias][$Model->displayField])) {
  543. $logData['title'] = $Model->data[$Model->alias][$Model->displayField];
  544. } elseif ($Model->id && $title = $Model->field($Model->displayField)) {
  545. $logData['title'] = $title;
  546. } elseif (!empty($logData[$this->settings[$Model->alias]['foreignKey']])) {
  547. $options = array(
  548. 'conditions' => $logData[$this->settings[$Model->alias]['foreignKey']],
  549. 'recursive' => -1
  550. );
  551. $record = $Model->find('first', $options);
  552. if ($record) {
  553. $logData['title'] = $record[$Model->alias][$Model->displayField];
  554. }
  555. }
  556. if ($this->Log->hasField($this->settings[$Model->alias]['classField'])) {
  557. $logData[$this->settings[$Model->alias]['classField']] = $Model->name;
  558. }
  559. if ($this->Log->hasField($this->settings[$Model->alias]['foreignKey']) && !isset($logData[$this->settings[$Model->alias]['foreignKey']])) {
  560. if ($Model->id) {
  561. $logData[$this->settings[$Model->alias]['foreignKey']] = $Model->id;
  562. } elseif ($Model->insertId) {
  563. $logData[$this->settings[$Model->alias]['foreignKey']] = $Model->insertId;
  564. }
  565. }
  566. if (!$this->Log->hasField('action')) {
  567. unset($logData['action']);
  568. } elseif (isset($Model->logableAction) && !empty($Model->logableAction)) {
  569. $logData['action'] = implode(',', $Model->logableAction);
  570. }
  571. if ($this->Log->hasField('version_id') && isset($Model->versionId)) {
  572. $logData['version_id'] = $Model->versionId;
  573. }
  574. if ($this->Log->hasField('ip') && $this->userIP) {
  575. $logData['ip'] = $this->userIP;
  576. }
  577. if ($this->Log->hasField($this->settings[$Model->alias]['userKey']) && $this->user && isset($this->user[$this->UserModel->alias])) {
  578. $logData[$this->settings[$Model->alias]['userKey']] = $this->user[$this->UserModel->alias][$this->UserModel->primaryKey];
  579. }
  580. if ($this->Log->hasField('description')) {
  581. if (empty($logData['description'])) {
  582. $logData['description'] = __('Custom action');
  583. }
  584. if ($this->user && $this->UserModel && isset($this->user[$this->UserModel->alias])) {
  585. $logData['description'] .= ' ' . __('by') . ' ' . $this->settings[$Model->alias]['userModel'] . ' "' . $this->user[$this->UserModel->alias][$this->UserModel->displayField] . '"';
  586. if ($this->settings[$Model->alias]['descriptionIds']) {
  587. $logData['description'] .= ' (' . $this->user[$this->UserModel->alias][$this->UserModel->primaryKey] . ')';
  588. }
  589. } else {
  590. // UserModel is active, but the data hasnt been set. Assume system action.
  591. $logData['description'] .= ' ' . __('by System');
  592. }
  593. $logData['description'] .= '.';
  594. }
  595. if (empty($logData['title'])) {
  596. // Fallback in case the title is null - add the action + ed
  597. $logData['title'] = $Model->alias . ' ' . $logData['action'] . 'ed';
  598. }
  599. $this->Log->create($logData);
  600. return $this->Log->save(null, array('validate' => false, 'callbacks' => false));
  601. }
  602. }