SoftDeleteBehavior.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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 http://opensource.org/licenses/mit-license.php MIT
  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. */
  27. class SoftDeleteBehavior extends ModelBehavior {
  28. /**
  29. * Default settings
  30. *
  31. * @var array
  32. */
  33. protected $_defaultConfig = [
  34. 'attribute' => 'softDeleted',
  35. 'fields' => [
  36. 'deleted' => 'deleted_date'
  37. ]
  38. ];
  39. /**
  40. * Holds activity flags for models
  41. *
  42. * @var array
  43. */
  44. public $runtime = [];
  45. /**
  46. * Setup callback
  47. *
  48. * @param Model $model
  49. * @param array $config
  50. * @return void
  51. */
  52. public function setup(Model $model, $config = []) {
  53. $config += $this->_defaultConfig;
  54. $error = 'SoftDeleteBehavior::setup(): model ' . $model->alias . ' has no field ';
  55. $fields = $this->_normalizeFields($model, $config['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] = ['fields' => $fields] + $config;
  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 Model $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'] = [];
  84. }
  85. $conditions = array_filter(array_keys($query['conditions']));
  86. $fields = $this->_normalizeFields($model);
  87. foreach ($fields as $flag => $date) {
  88. if ($runtime === true || $flag === $runtime) {
  89. if (!in_array($flag, $conditions) && !in_array($model->alias . '.' . $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 Model $model
  104. * @param array $query
  105. * @return bool Success
  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 Model $model
  122. * @param int $id
  123. * @return bool Success
  124. */
  125. public function delete(Model $model, $id) {
  126. $runtime = $this->runtime[$model->alias];
  127. $data = [];
  128. $fields = $this->_normalizeFields($model);
  129. foreach ($fields as $flag => $date) {
  130. if ($runtime === true || $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. $keys = $this->_getCounterCacheKeys($model, $id);
  141. $model->create();
  142. $model->set($model->primaryKey, $id);
  143. $options = [
  144. 'validate' => false,
  145. 'fieldList' => array_keys($data),
  146. 'counterCache' => false
  147. ];
  148. $result = (bool)$model->save([$model->alias => $data], $options);
  149. if ($result && !empty($keys[$model->alias])) {
  150. $model->updateCounterCache($keys[$model->alias]);
  151. }
  152. return $result;
  153. }
  154. /**
  155. * Mark record as not deleted
  156. *
  157. * @param Model $model
  158. * @param int $id
  159. * @return bool Success
  160. */
  161. public function undelete(Model $model, $id) {
  162. $runtime = $this->runtime[$model->alias];
  163. $this->softDelete($model, false);
  164. $data = [];
  165. $fields = $this->_normalizeFields($model);
  166. foreach ($fields as $flag => $date) {
  167. if ($runtime === true || $flag === $runtime) {
  168. $data[$flag] = false;
  169. if ($date) {
  170. $data[$date] = null;
  171. }
  172. if ($flag === $runtime) {
  173. break;
  174. }
  175. }
  176. }
  177. $model->create();
  178. $model->set($model->primaryKey, $id);
  179. $options = [
  180. 'validate' => false,
  181. 'fieldList' => array_keys($data),
  182. 'counterCache' => false
  183. ];
  184. $result = $model->save([$model->alias => $data], $options);
  185. $this->softDelete($model, $runtime);
  186. if ($result) {
  187. $keys = $this->_getCounterCacheKeys($model, $id);
  188. if (!empty($keys[$model->alias])) {
  189. $model->updateCounterCache($keys[$model->alias]);
  190. }
  191. }
  192. return $result;
  193. }
  194. /**
  195. * Enable/disable SoftDelete functionality
  196. *
  197. * Usage from model:
  198. * $this->softDelete(false); deactivate this behavior for model
  199. * $this->softDelete('field_two'); enabled only for this flag field
  200. * $this->softDelete(true); enable again for all flag fields
  201. * $config = $this->softDelete(null); for obtaining current setting
  202. *
  203. * @param Model $model
  204. * @param mixed $active
  205. * @return mixed If $active is null, then current setting/null, or boolean if runtime setting for model was changed
  206. */
  207. public function softDelete(Model $model, $active) {
  208. if ($active === null) {
  209. return isset($this->runtime[$model->alias]) ? $this->runtime[$model->alias] : null;
  210. }
  211. $result = !isset($this->runtime[$model->alias]) || $this->runtime[$model->alias] !== $active;
  212. $this->runtime[$model->alias] = $active;
  213. $this->_softDeleteAssociations($model, $active);
  214. return $result;
  215. }
  216. /**
  217. * Returns number of outdated softdeleted records prepared for purge
  218. *
  219. * @param Model $model
  220. * @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
  221. * @return int
  222. */
  223. public function purgeDeletedCount(Model $model, $expiration = '-90 days') {
  224. $this->softDelete($model, false);
  225. return $model->find('count', ['conditions' => $this->_purgeDeletedConditions($model, $expiration), 'recursive' => -1]);
  226. }
  227. /**
  228. * Purge table
  229. *
  230. * @param Model $model
  231. * @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
  232. * @return bool If there were some outdated records
  233. */
  234. public function purgeDeleted(Model $model, $expiration = '-90 days') {
  235. $this->softDelete($model, false);
  236. $records = $model->find('all', [
  237. 'conditions' => $this->_purgeDeletedConditions($model, $expiration),
  238. 'fields' => [$model->primaryKey],
  239. 'recursive' => -1]);
  240. if ($records) {
  241. foreach ($records as $record) {
  242. $model->delete($record[$model->alias][$model->primaryKey]);
  243. }
  244. return true;
  245. }
  246. return false;
  247. }
  248. /**
  249. * Returns conditions for finding outdated records
  250. *
  251. * @param Model $model
  252. * @param mixed $expiration anything parseable by strtotime(), by default '-90 days'
  253. * @return array
  254. */
  255. protected function _purgeDeletedConditions(Model $model, $expiration = '-90 days') {
  256. $purgeDate = date('Y-m-d H:i:s', strtotime($expiration));
  257. $conditions = [];
  258. foreach ($this->settings[$model->alias]['fields'] as $flag => $date) {
  259. $conditions[$model->alias . '.' . $flag] = true;
  260. if ($date) {
  261. $conditions[$model->alias . '.' . $date . ' <'] = $purgeDate;
  262. }
  263. }
  264. return $conditions;
  265. }
  266. /**
  267. * Return normalized field array
  268. *
  269. * @param Model $model
  270. * @param array $config
  271. * @return array
  272. */
  273. protected function _normalizeFields(Model $model, $config = []) {
  274. if (empty($config)) {
  275. $config = $this->settings[$model->alias]['fields'];
  276. }
  277. $result = [];
  278. foreach ($config as $flag => $date) {
  279. if (is_numeric($flag)) {
  280. $flag = $date;
  281. $date = false;
  282. }
  283. $result[$flag] = $date;
  284. }
  285. return $result;
  286. }
  287. /**
  288. * Modifies conditions of hasOne and hasMany associations.
  289. *
  290. * If multiple delete flags are configured for model, then $active=true doesn't
  291. * do anything - you have to alter conditions in association definition
  292. *
  293. * @param Model $model
  294. * @param mixed $active
  295. * @return void
  296. */
  297. protected function _softDeleteAssociations(Model $model, $active) {
  298. if (empty($model->belongsTo)) {
  299. return;
  300. }
  301. $fields = array_keys($this->_normalizeFields($model));
  302. $parentModels = array_keys($model->belongsTo);
  303. foreach ($parentModels as $parentModel) {
  304. foreach (['hasOne', 'hasMany'] as $assocType) {
  305. if (empty($model->{$parentModel}->{$assocType})) {
  306. continue;
  307. }
  308. foreach ($model->{$parentModel}->{$assocType} as $assoc => $assocConfig) {
  309. $modelName = !empty($assocConfig['className']) ? $assocConfig['className'] : $assoc;
  310. if ($model->alias !== $modelName) {
  311. continue;
  312. }
  313. $conditions = $model->{$parentModel}->{$assocType}[$assoc]['conditions'];
  314. if (!is_array($conditions)) {
  315. $model->{$parentModel}->{$assocType}[$assoc]['conditions'] = [];
  316. }
  317. $multiFields = 1 < count($fields);
  318. foreach ($fields as $field) {
  319. if ($active) {
  320. if (!isset($conditions[$field]) && !isset($conditions[$assoc . '.' . $field])) {
  321. if (is_string($active)) {
  322. if ($field === $active) {
  323. $conditions[$assoc . '.' . $field] = false;
  324. } elseif (isset($conditions[$assoc . '.' . $field])) {
  325. unset($conditions[$assoc . '.' . $field]);
  326. }
  327. } elseif (!$multiFields) {
  328. $conditions[$assoc . '.' . $field] = false;
  329. }
  330. }
  331. } elseif (isset($conditions[$assoc . '.' . $field])) {
  332. unset($conditions[$assoc . '.' . $field]);
  333. }
  334. }
  335. }
  336. }
  337. }
  338. }
  339. /**
  340. * Retrieves the foreign key values for the `belongsTo` associations
  341. * with enabled counter caching.
  342. *
  343. * The returned array has the following format:
  344. *
  345. * {{{
  346. * array(
  347. * 'ModelAlias' => array(
  348. * 'foreign_key_name' => foreign key value
  349. * )
  350. * )
  351. * }}}
  352. *
  353. * @param Model $model
  354. * @param int $id The ID of the current record
  355. * @return array
  356. */
  357. protected function _getCounterCacheKeys(Model $model, $id) {
  358. $keys = [];
  359. if (!empty($model->belongsTo)) {
  360. $fields = [];
  361. foreach ($model->belongsTo as $alias => $assoc) {
  362. if (!empty($assoc['counterCache']) && isset($assoc['foreignKey']) && is_string($assoc['foreignKey'])) {
  363. $fields[$alias] = $assoc['foreignKey'];
  364. }
  365. }
  366. if (!empty($fields)) {
  367. $keys = $model->find('first', [
  368. 'fields' => $fields,
  369. 'conditions' => [$model->alias . '.' . $model->primaryKey => $id],
  370. 'recursive' => -1,
  371. 'callbacks' => false
  372. ]);
  373. }
  374. }
  375. return $keys;
  376. }
  377. }