WhoDidItBehavior.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. <?php
  2. /**
  3. * PHP 5
  4. *
  5. * @copyright http://www.4webby.com
  6. * @author Daniel Vecchiato
  7. * @author Mark Scherer
  8. * @author Marc Würth
  9. * @version 1.3
  10. * @license http://opensource.org/licenses/mit-license.php MIT
  11. */
  12. App::uses('AuthComponent', 'Controller/Component');
  13. App::uses('CakeSession', 'Model/Datasource');
  14. App::uses('ModelBehavior', 'Model');
  15. /**
  16. * WhoDidIt Behavior
  17. *
  18. * Handles created_by, modified_by fields for a given Model, if they exist in the Model DB table.
  19. * It's similar to the created, modified automagic, but it stores the id of the logged in user
  20. * in the models that have $actsAs = array('WhoDidIt').
  21. *
  22. * This is useful to track who created records, and the last user that has changed them.
  23. *
  24. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#using-created-and-modified
  25. */
  26. class WhoDidItBehavior extends ModelBehavior {
  27. /**
  28. * Default config for a model that has this behavior attached.
  29. *
  30. * Setting force_modified to true will have the same effect as overriding the save method as
  31. * described in the code example for "Using created and modified" in the Cookbook.
  32. *
  33. * @var array
  34. * @link http://book.cakephp.org/2.0/en/models/saving-your-data.html#using-created-and-modified
  35. */
  36. protected $_defaultConfig = [
  37. 'auth_session' => 'Auth', // Name of Auth session key
  38. 'user_model' => 'User', // Name of the User model (for plugins use PluginName.ModelName)
  39. 'created_by_field' => 'created_by', // Name of the "created_by" field in the model
  40. 'modified_by_field' => 'modified_by', // Name of the "modified_by" field in the model
  41. 'confirmed_by_field' => 'confirmed_by', // Name of the "confirmed by" field in the model
  42. 'auto_bind' => true, // Automatically bind the model to the User model (default true)
  43. 'force_modified' => false // Force update of the "modified" field even if not empty
  44. ];
  45. /**
  46. * Initiate WhoDidIt Behavior.
  47. *
  48. * Checks if the configured fields are available in the model.
  49. * Also binds the User model as association for each available field.
  50. *
  51. * @param Model $Model The model.
  52. * @param array $config Behavior settings you would like to override.
  53. * @return void
  54. */
  55. public function setup(Model $Model, $config = []) {
  56. $config += $this->_defaultConfig;
  57. $config['has_created_by'] = $Model->hasField($config['created_by_field']);
  58. $config['has_modified_by'] = $Model->hasField($config['modified_by_field']);
  59. $config['has_confirmed_by'] = $Model->hasField($config['confirmed_by_field']);
  60. // Handles model binding to the User model according to the auto_bind settings (default true).
  61. if ($config['auto_bind']) {
  62. if ($config['has_created_by']) {
  63. $commonBelongsTo = [
  64. 'CreatedBy' => [
  65. 'className' => $config['user_model'],
  66. 'foreignKey' => $config['created_by_field']]];
  67. $Model->bindModel(['belongsTo' => $commonBelongsTo], false);
  68. }
  69. if ($config['has_modified_by']) {
  70. $commonBelongsTo = [
  71. 'ModifiedBy' => [
  72. 'className' => $config['user_model'],
  73. 'foreignKey' => $config['modified_by_field']]];
  74. $Model->bindModel(['belongsTo' => $commonBelongsTo], false);
  75. }
  76. if ($config['has_confirmed_by']) {
  77. $commonBelongsTo = [
  78. 'ConfirmedBy' => [
  79. 'className' => $config['user_model'],
  80. 'foreignKey' => $config['confirmed_by_field']]];
  81. $Model->bindModel(['belongsTo' => $commonBelongsTo], false);
  82. }
  83. }
  84. $this->settings[$Model->alias] = $config;
  85. }
  86. /**
  87. * Before save callback.
  88. *
  89. * Checks if at least one field is available.
  90. * Reads the current user id from the session.
  91. * If a user id is set it will fill...
  92. * ... the created_by field only when creating a record
  93. * ... the modified by field only if it is not in the data array
  94. * or the "force_modified" setting is set to true.
  95. *
  96. * @param Model $Model The Model using this behavior
  97. * @param array $options Options passed from Model::save(), unused.
  98. * @return mixed False if the operation should abort. Any other result will continue.
  99. * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  100. */
  101. public function beforeSave(Model $Model, $options = []) {
  102. $config = $this->settings[$Model->alias];
  103. if (!$config['has_created_by'] && !$config['has_modified_by']) {
  104. return true;
  105. }
  106. $authSession = $config['auth_session'];
  107. list(, $userSession) = pluginSplit($config['user_model']);
  108. $userId = AuthComponent::user('id');
  109. if (empty($userId)) {
  110. $userId = CakeSession::read($authSession . '.' . $userSession . '.id');
  111. }
  112. if (!$userId) {
  113. return true;
  114. }
  115. $data = [];
  116. $modifiedByField = $config['modified_by_field'];
  117. if (!isset($Model->data[$Model->alias][$modifiedByField]) || $config['force_modified']) {
  118. $data[$config['modified_by_field']] = $userId;
  119. } else {
  120. $pos = strpos($config['modified_by_field'], '_');
  121. $field = substr($config['modified_by_field'], 0, $pos);
  122. $data[$field] = false;
  123. }
  124. if (!$Model->exists()) {
  125. $data[$config['created_by_field']] = $userId;
  126. }
  127. if ($data) {
  128. $Model->set($data);
  129. }
  130. return true;
  131. }
  132. }