SoftDeleteBehavior.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <?php
  2. /**
  3. * Copyright 2007-2010, Cake Development Corporation (http://cakedc.com)
  4. *
  5. * Licensed under The MIT License
  6. * Redistributions of files must retain the above copyright notice.
  7. *
  8. * @copyright Copyright 2007-2010, Cake Development Corporation (http://cakedc.com)
  9. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  10. */
  11. App::uses('ModelBehavior', 'Model');
  12. /**
  13. * Soft Delete Behavior
  14. *
  15. * Note: To make delete() return true with SoftDelete attached, you need to modify your AppModel and overwrite
  16. * delete() there:
  17. *
  18. * public function delete($id = null, $cascade = true) {
  19. * $result = parent::delete($id, $cascade);
  20. * if (!$result && $this->Behaviors->loaded('SoftDelete')) {
  21. * return $this->softDeleted;
  22. * }
  23. * return $result;
  24. * }
  25. *
  26. * 2013-04-16 ms
  27. */
  28. class SoftDeleteBehavior extends ModelBehavior {
  29. /**
  30. * Default settings
  31. *
  32. * @var array
  33. */
  34. protected $_defaults = array(
  35. 'attribute' => 'softDeleted',
  36. 'fields' => array(
  37. 'deleted' => 'deleted_date'
  38. )
  39. );
  40. /**
  41. * Holds activity flags for models
  42. *
  43. * @var array
  44. */
  45. public $runtime = array();
  46. /**
  47. * Setup callback
  48. *
  49. * @param object $model
  50. * @param array $settings
  51. */
  52. public function setup(Model $model, $settings = array()) {
  53. $settings = array_merge($this->_defaults, $settings);
  54. $error = 'SoftDeleteBehavior::setup(): model ' . $model->alias . ' has no field ';
  55. $fields = $this->_normalizeFields($model, $settings['fields']);
  56. foreach ($fields as $flag => $date) {
  57. if ($model->hasField($flag)) {
  58. if ($date && !$model->hasField($date)) {
  59. trigger_error($error . $date, E_USER_NOTICE);
  60. return;
  61. }
  62. continue;
  63. }
  64. trigger_error($error . $flag, E_USER_NOTICE);
  65. return;
  66. }
  67. $this->settings[$model->alias] = array_merge($settings, array('fields' => $fields));
  68. $this->softDelete($model, true);
  69. $attribute = $this->settings[$model->alias]['attribute'];
  70. $model->$attribute = false;
  71. }
  72. /**
  73. * Before find callback
  74. *
  75. * @param object $model
  76. * @param array $query
  77. * @return array
  78. */
  79. public function beforeFind(Model $model, $query) {
  80. $runtime = $this->runtime[$model->alias];
  81. if ($runtime) {
  82. if (!is_array($query['conditions'])) {
  83. $query['conditions'] = array();
  84. }
  85. $conditions = array_filter(array_keys($query['conditions']));
  86. $fields = $this->_normalizeFields($model);
  87. foreach ($fields as $flag => $date) {
  88. if (true === $runtime || $flag === $runtime) {
  89. if (!in_array($flag, $conditions) && !in_array($model->name . '.' . $flag, $conditions)) {
  90. $query['conditions'][$model->alias . '.' . $flag] = false;
  91. }
  92. if ($flag === $runtime) {
  93. break;
  94. }
  95. }
  96. }
  97. return $query;
  98. }
  99. }
  100. /**
  101. * Before delete callback
  102. *
  103. * @param object $model
  104. * @param array $query
  105. * @return boolean
  106. */
  107. public function beforeDelete(Model $model, $cascade = true) {
  108. $runtime = $this->runtime[$model->alias];
  109. if ($runtime) {
  110. if ($this->delete($model, $model->id)) {
  111. $attribute = $this->settings[$model->alias]['attribute'];
  112. $model->$attribute = true;
  113. }
  114. return false;
  115. }
  116. return true;
  117. }
  118. /**
  119. * Mark record as deleted
  120. *
  121. * @param object $model
  122. * @param integer $id
  123. * @return boolean
  124. */
  125. public function delete(Model $model, $id) {
  126. $runtime = $this->runtime[$model->alias];
  127. $data = array();
  128. $fields = $this->_normalizeFields($model);
  129. foreach ($fields as $flag => $date) {
  130. if (true === $runtime || $flag === $runtime) {
  131. $data[$flag] = true;
  132. if ($date) {
  133. $data[$date] = date('Y-m-d H:i:s');
  134. }
  135. if ($flag === $runtime) {
  136. break;
  137. }
  138. }
  139. }
  140. $model->create();
  141. $model->set($model->primaryKey, $id);
  142. return $model->save(array($model->alias => $data), false, array_keys($data));
  143. }
  144. /**
  145. * Mark record as not deleted
  146. *
  147. * @param object $model
  148. * @param integer $id
  149. * @return boolean
  150. */
  151. public function undelete(Model $model, $id) {
  152. $runtime = $this->runtime[$model->alias];
  153. $this->softDelete($model, false);
  154. $data = array();
  155. $fields = $this->_normalizeFields($model);
  156. foreach ($fields as $flag => $date) {
  157. if (true === $runtime || $flag === $runtime) {
  158. $data[$flag] = false;
  159. if ($date) {
  160. $data[$date] = null;
  161. }
  162. if ($flag === $runtime) {
  163. break;
  164. }
  165. }
  166. }
  167. $model->create();
  168. $model->set($model->primaryKey, $id);
  169. $result = $model->save(array($model->alias => $data), false, array_keys($data));
  170. $this->softDelete($model, $runtime);
  171. return $result;
  172. }
  173. /**
  174. * Enable/disable SoftDelete functionality
  175. *
  176. * Usage from model:
  177. * $this->softDelete(false); deactivate this behavior for model
  178. * $this->softDelete('field_two'); enabled only for this flag field
  179. * $this->softDelete(true); enable again for all flag fields
  180. * $config = $this->softDelete(null); for obtaining current setting
  181. *
  182. * @param object $model
  183. * @param mixed $active
  184. * @return mixed if $active is null, then current setting/null, or boolean if runtime setting for model was changed
  185. */
  186. public function softDelete(Model $model, $active) {
  187. if (is_null($active)) {
  188. return !empty($this->runtime[$model->alias]) ? $this->runtime[$model->alias] : null;
  189. }
  190. $result = !isset($this->runtime[$model->alias]) || $this->runtime[$model->alias] !== $active;
  191. $this->runtime[$model->alias] = $active;
  192. $this->_softDeleteAssociations($model, $active);
  193. return $result;
  194. }
  195. /**
  196. * Returns number of outdated softdeleted records prepared for purge
  197. *
  198. * @param object $model
  199. * @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
  200. * @return integer
  201. */
  202. public function purgeDeletedCount(Model $model, $expiration = '-90 days') {
  203. $this->softDelete($model, false);
  204. return $model->find('count', array('conditions' => $this->_purgeDeletedConditions($model, $expiration), 'recursive' => -1));
  205. }
  206. /**
  207. * Purge table
  208. *
  209. * @param object $model
  210. * @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
  211. * @return boolean if there were some outdated records
  212. */
  213. public function purgeDeleted(Model $model, $expiration = '-90 days') {
  214. $this->softDelete($model, false);
  215. $records = $model->find('all', array(
  216. 'conditions' => $this->_purgeDeletedConditions($model, $expiration),
  217. 'fields' => array($model->primaryKey),
  218. 'recursive' => -1));
  219. if ($records) {
  220. foreach ($records as $record) {
  221. $model->delete($record[$model->alias][$model->primaryKey]);
  222. }
  223. return true;
  224. }
  225. return false;
  226. }
  227. /**
  228. * Returns conditions for finding outdated records
  229. *
  230. * @param object $model
  231. * @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
  232. * @return array
  233. */
  234. protected function _purgeDeletedConditions(Model $model, $expiration = '-90 days') {
  235. $purgeDate = date('Y-m-d H:i:s', strtotime($expiration));
  236. $conditions = array();
  237. foreach ($this->settings[$model->alias]['fields'] as $flag => $date) {
  238. $conditions[$model->alias . '.' . $flag] = true;
  239. if ($date) {
  240. $conditions[$model->alias . '.' . $date . ' <'] = $purgeDate;
  241. }
  242. }
  243. return $conditions;
  244. }
  245. /**
  246. * Return normalized field array
  247. *
  248. * @param object $model
  249. * @param array $settings
  250. * @return array
  251. */
  252. protected function _normalizeFields(Model $model, $settings = array()) {
  253. if (empty($settings)) {
  254. $settings = $this->settings[$model->alias]['fields'];
  255. }
  256. $result = array();
  257. foreach ($settings as $flag => $date) {
  258. if (is_numeric($flag)) {
  259. $flag = $date;
  260. $date = false;
  261. }
  262. $result[$flag] = $date;
  263. }
  264. return $result;
  265. }
  266. /**
  267. * Modifies conditions of hasOne and hasMany associations
  268. *
  269. * If multiple delete flags are configured for model, then $active=true doesn't
  270. * do anything - you have to alter conditions in association definition
  271. *
  272. * @param object $model
  273. * @param mixed $active
  274. */
  275. protected function _softDeleteAssociations(Model $model, $active) {
  276. if (empty($model->belongsTo)) {
  277. return;
  278. }
  279. $fields = array_keys($this->_normalizeFields($model));
  280. $parentModels = array_keys($model->belongsTo);
  281. foreach ($parentModels as $parentModel) {
  282. foreach (array('hasOne', 'hasMany') as $assocType) {
  283. if (empty($model->{$parentModel}->{$assocType})) {
  284. continue;
  285. }
  286. foreach ($model->{$parentModel}->{$assocType} as $assoc => $assocConfig) {
  287. $modelName = !empty($assocConfig['className']) ? $assocConfig['className'] : $assoc;
  288. if ($model->alias != $modelName) {
  289. continue;
  290. }
  291. $conditions = $model->{$parentModel}->{$assocType}[$assoc]['conditions'];
  292. if (!is_array($conditions)) {
  293. $model->{$parentModel}->{$assocType}[$assoc]['conditions'] = array();
  294. }
  295. $multiFields = 1 < count($fields);
  296. foreach ($fields as $field) {
  297. if ($active) {
  298. if (!isset($conditions[$field]) && !isset($conditions[$assoc . '.' . $field])) {
  299. if (is_string($active)) {
  300. if ($field == $active) {
  301. $conditions[$assoc . '.' . $field] = false;
  302. } elseif (isset($conditions[$assoc . '.' . $field])) {
  303. unset($conditions[$assoc . '.' . $field]);
  304. }
  305. } elseif (!$multiFields) {
  306. $conditions[$assoc . '.' . $field] = false;
  307. }
  308. }
  309. } elseif (isset($conditions[$assoc . '.' . $field])) {
  310. unset($conditions[$assoc . '.' . $field]);
  311. }
  312. }
  313. }
  314. }
  315. }
  316. }
  317. }