| 1 |
<?php |
| 2 |
/** |
| 3 |
* Daily cleanup for the email log table. |
| 4 |
* |
| 5 |
* Separate from LogCleanup (which manages storeengine_logs) because the |
| 6 |
* retention policy is different: customer-communication history wants longer |
| 7 |
* retention for failures (deliverability debugging) and shorter for routine |
| 8 |
* successes. Both clean up independently. |
| 9 |
* |
| 10 |
* @version 1.0.0 |
| 11 |
*/ |
| 12 |
|
| 13 |
namespace StoreEngine\Classes; |
| 14 |
|
| 15 |
if ( ! defined( 'ABSPATH' ) ) { |
| 16 |
exit; |
| 17 |
} |
| 18 |
|
| 19 |
class EmailLogCleanup { |
| 20 |
|
| 21 |
const DEFAULT_RETENTION_SENT = 90; |
| 22 |
const DEFAULT_RETENTION_FAILED = 365; |
| 23 |
|
| 24 |
public static function execute_cleanup() { |
| 25 |
$settings = self::get_settings(); |
| 26 |
|
| 27 |
$days_sent = (int) $settings['retention_days_sent']; |
| 28 |
$days_failed = (int) $settings['retention_days_failed']; |
| 29 |
|
| 30 |
if ( $days_sent > 0 ) { |
| 31 |
self::purge( 'sent', $days_sent ); |
| 32 |
} |
| 33 |
|
| 34 |
if ( $days_failed > 0 ) { |
| 35 |
self::purge( 'failed', $days_failed ); |
| 36 |
} |
| 37 |
|
| 38 |
// 'queued' rows older than 1 day are almost always stuck — wp_mail |
| 39 |
// didn't fire the success/fail action, or the request died. Purge them |
| 40 |
// after the same window as sent so they don't accumulate. |
| 41 |
if ( $days_sent > 0 ) { |
| 42 |
self::purge( 'queued', $days_sent ); |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
public static function get_settings(): array { |
| 47 |
$defaults = [ |
| 48 |
'retention_days_sent' => self::DEFAULT_RETENTION_SENT, |
| 49 |
'retention_days_failed' => self::DEFAULT_RETENTION_FAILED, |
| 50 |
]; |
| 51 |
|
| 52 |
$stored = get_option( 'storeengine_email_log_settings', [] ); |
| 53 |
|
| 54 |
if ( ! is_array( $stored ) ) { |
| 55 |
$stored = []; |
| 56 |
} |
| 57 |
|
| 58 |
return array_merge( $defaults, $stored ); |
| 59 |
} |
| 60 |
|
| 61 |
protected static function purge( string $status, int $days ) { |
| 62 |
global $wpdb; |
| 63 |
$table = $wpdb->prefix . 'storeengine_email_log'; |
| 64 |
$threshold = gmdate( 'Y-m-d H:i:s', time() - ( $days * DAY_IN_SECONDS ) ); |
| 65 |
|
| 66 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Prepared (%i/%s) delete on a custom StoreEngine log table; retention cleanup, not cacheable. |
| 67 |
$wpdb->query( |
| 68 |
$wpdb->prepare( |
| 69 |
'DELETE FROM %i WHERE status = %s AND sent_at_gmt < %s', |
| 70 |
$table, |
| 71 |
$status, |
| 72 |
$threshold |
| 73 |
) |
| 74 |
); |
| 75 |
} |
| 76 |
} |
| 77 |
|