Plugin Directory

Changeset 3808895


Ignore:
Timestamp:
11/18/2026 09:08:47 AM (12 days ago)
Author:
siteskite
Message:

Release 2.2.14: improved backup reliability.

Location:
siteskite/trunk
Files:
14 edited

Legend:

Unmodified
Added
Removed
  • siteskite/trunk/includes/API/FallbackAPI.php

    r3771884 r3808895  
    429429            '/backup/callback' => [[$this->rest_api, 'set_callback'], ['POST']],
    430430            '/backup/list-active' => [[$this->rest_api, 'handle_list_active_backups'], ['GET']],
     431            '/backup/resume-stale' => [[$this->rest_api, 'handle_backup_resume_stale'], ['POST']],
    431432            '/backup/clear-all' => [[$this->rest_api, 'handle_clear_all_backups'], ['POST', 'DELETE']],
    432433            '/backup/cleanup' => [[$this->rest_api, 'handle_backup_cleanup'], ['POST', 'DELETE']],
  • siteskite/trunk/includes/API/RestAPI.php

    r3771884 r3808895  
    312312        ]);
    313313
     314        // Laravel watcher re-knock for one stuck backup. Auth = Connect API key only
     315        // (same as other backup routes). Does not use cron secret or Login As Ed25519.
     316        register_rest_route(self::API_NAMESPACE, '/backup/resume-stale', [
     317            'methods' => WP_REST_Server::CREATABLE,
     318            'callback' => [$this, 'handle_backup_resume_stale'],
     319            'permission_callback' => [$this->auth_manager, 'verify_request'],
     320            'args' => [
     321                'backup_id' => [
     322                    'required' => true,
     323                    'type' => 'string',
     324                    'sanitize_callback' => 'sanitize_text_field',
     325                ],
     326            ],
     327        ]);
     328
    314329        register_rest_route(self::API_NAMESPACE, '/backup/clear-all', [
    315330            'methods' => WP_REST_Server::CREATABLE,
    … …  
    9981013
    9991014    /**
     1015     * Resume one stuck in-progress backup (Laravel watcher → Connect API key).
     1016     *
     1017     * Security bounds:
     1018     * - Auth is verify_request (site Connect key), not cron secret / Ed25519 Login As.
     1019     * - backup_id is required and format-checked.
     1020     * - Only resumes an existing local backup record that is still non-terminal.
     1021     * - Response is minimal (no paths, keys, or internal option dumps).
     1022     */
     1023    public function handle_backup_resume_stale(WP_REST_Request $request): WP_REST_Response
     1024    {
     1025        try {
     1026            $backup_id = sanitize_text_field((string) ($request->get_param('backup_id') ?? ''));
     1027            if ($backup_id === '' || !preg_match('/^[a-zA-Z0-9_]+$/', $backup_id)) {
     1028                return rest_ensure_response([
     1029                    'success' => false,
     1030                    'message' => 'A valid backup_id is required',
     1031                ], 400);
     1032            }
     1033
     1034            $backup_info = get_option(\SiteSkite\Backup\BackupManager::OPTION_PREFIX . $backup_id);
     1035            if (!is_array($backup_info) || $backup_info === []) {
     1036                return rest_ensure_response([
     1037                    'success' => false,
     1038                    'message' => 'Backup not found',
     1039                    'backup_id' => $backup_id,
     1040                ], 404);
     1041            }
     1042
     1043            $status = (string) ($backup_info['status'] ?? '');
     1044            if (in_array($status, ['completed', 'failed', 'cancelled'], true)) {
     1045                return rest_ensure_response([
     1046                    'success' => true,
     1047                    'message' => 'Backup already finished',
     1048                    'backup_id' => $backup_id,
     1049                    'status' => $status,
     1050                    'resumed' => false,
     1051                ]);
     1052            }
     1053
     1054            if (!in_array($status, ['initializing', 'processing', 'uploading', 'pending'], true)) {
     1055                return rest_ensure_response([
     1056                    'success' => false,
     1057                    'message' => 'Backup status is not resumable',
     1058                    'backup_id' => $backup_id,
     1059                    'status' => $status,
     1060                ], 409);
     1061            }
     1062
     1063            $this->backup_manager->ensure_backup_resume_safety_net($backup_id);
     1064            $result = $this->backup_manager->handle_backup_resume_safety_net($backup_id);
     1065            if (!empty($result['reschedule_safety_net'])) {
     1066                $this->backup_manager->ensure_backup_resume_safety_net($backup_id, true);
     1067            }
     1068
     1069            return rest_ensure_response([
     1070                'success' => true,
     1071                'message' => 'Resume check completed',
     1072                'backup_id' => $backup_id,
     1073                'status' => (string) ($result['status'] ?? ''),
     1074                'resumed' => !empty($result['resumed']),
     1075            ]);
     1076        } catch (\Exception $e) {
     1077            $this->logger->error('Failed to resume stale backup', [
     1078                'error' => $e->getMessage(),
     1079            ]);
     1080            return rest_ensure_response([
     1081                'success' => false,
     1082                'message' => 'Resume check failed',
     1083            ], 500);
     1084        }
     1085    }
     1086
     1087    /**
    10001088     * Handle clear all backups request
    10011089     */
    … …  
    14371525                'day' => $request->get_param('day'),
    14381526                'date' => (int) $request->get_param('date'),
     1527                'timezone' => $request->get_param('timezone') ?: 'UTC',
    14391528                'callback_url' => $request->get_param('callback_url'),
    14401529            ];
  • siteskite/trunk/includes/Auth/AuthManager.php

    r3707290 r3808895  
    141141            }
    142142
    143             // Check if this API key is already stored and validated
    144143            $stored_key = get_option(self::API_KEY_OPTION);
    145             if ($stored_key === $api_key) {
    146                 // Refresh portal Login As public key even when already linked.
     144            $already_stored = is_string($stored_key) && $stored_key !== '' && hash_equals($stored_key, $api_key);
     145
     146            // Always validate + register current domain. After a DB restore the key is
     147            // already in options, but the sandbox URL still needs add-connect-site.
     148            if (!$already_stored) {
     149                $validation_url = add_query_arg(['key' => $api_key], self::VALIDATION_ENDPOINT);
     150                $response = wp_remote_get($validation_url, [
     151                    'timeout' => 30,
     152                    'headers' => [
     153                        'Accept' => 'application/json',
     154                    ],
     155                ]);
     156
     157                if (is_wp_error($response)) {
     158                    throw new \RuntimeException('Failed to validate API key: ' . $response->get_error_message());
     159                }
     160
     161                $status_code = wp_remote_retrieve_response_code($response);
     162                $validation_body = wp_remote_retrieve_body($response);
     163                $validation_data = json_decode($validation_body, true);
     164
     165                if ($status_code !== 200 || !isset($validation_data['valid']) || !$validation_data['valid']) {
     166                    wp_send_json_error('Invalid API key');
     167                    return;
     168                }
     169
     170                if (!empty($validation_data['autologin_public_key']) && is_string($validation_data['autologin_public_key'])) {
     171                    \SiteSkite\Core\AutologinPortalSignature::storePublicKey(
     172                        (string) $validation_data['autologin_public_key'],
     173                        isset($validation_data['autologin_alg']) ? (string) $validation_data['autologin_alg'] : \SiteSkite\Core\AutologinPortalSignature::ALG
     174                    );
     175                }
     176            } else {
     177                // Refresh portal Login As public key when re-linking an existing key.
    147178                $validation_url = add_query_arg(['key' => $api_key], self::VALIDATION_ENDPOINT);
    148179                $refresh = wp_remote_get($validation_url, [
    … …  
    159190                    }
    160191                }
     192            }
     193
     194            $link_result = $this->register_site_with_portal($api_key);
     195            if ($link_result !== true) {
     196                $message = is_wp_error($link_result)
     197                    ? $link_result->get_error_message()
     198                    : 'Failed to link site. Please try again or contact support.';
     199                throw new \RuntimeException($message);
     200            }
     201
     202            if ($already_stored) {
    161203                wp_send_json_success(sprintf('API key already validated and site is linked with %s Portal', $display_name));
    162204                return;
    163205            }
    164206
    165             // Step 1: Validate API key
    166 
    167             $validation_url = add_query_arg(['key' => $api_key], self::VALIDATION_ENDPOINT);
    168             $response = wp_remote_get($validation_url, [
    169 
    170                 'timeout' => 30,
    171                 'headers' => [
    172                     'Accept' => 'application/json'
    173                 ]
    174 
    175             ]);
    176 
    177             if (is_wp_error($response)) {
    178                 throw new \RuntimeException('Failed to validate API key: ' . $response->get_error_message());
    179             }
    180 
    181             $status_code = wp_remote_retrieve_response_code($response);
    182             $validation_body = wp_remote_retrieve_body($response);
    183             $validation_data = json_decode($validation_body, true);
    184 
    185             if ($status_code !== 200 || !isset($validation_data['valid']) || !$validation_data['valid']) {
    186                 wp_send_json_error('Invalid API key');
    187                 return;
    188             }
    189 
    190             // Cache portal Login As verification material when provided.
    191             if (!empty($validation_data['autologin_public_key']) && is_string($validation_data['autologin_public_key'])) {
    192                 \SiteSkite\Core\AutologinPortalSignature::storePublicKey(
    193                     $validation_data['autologin_public_key'],
    194                     isset($validation_data['autologin_alg']) ? (string) $validation_data['autologin_alg'] : \SiteSkite\Core\AutologinPortalSignature::ALG
    195                 );
    196             }
    197 
    198             // Extract domain with path for subdirectory sites
    199             $site_url = get_site_url();
    200             $parsed_url = wp_parse_url($site_url);
    201             $host = $parsed_url['host'] ?? '';
    202             $path = isset($parsed_url['path']) ? rtrim($parsed_url['path'], '/') : '';
    203             $domain = $host . ($path ? $path : '');
    204 
    205             $site_data = [
    206                 'name' => get_bloginfo('name'),
    207                 'domain' => $domain,
    208                 'status' => '1',
    209                 'php_version' => PHP_VERSION,
    210                 'wp_version' => get_bloginfo('version'),
    211                 'token' => $api_key,
    212             ];
    213             $site_data = array_merge($site_data, Utils::get_rest_connectivity());
    214 
    215             $link_response = wp_remote_post(self::LINK_SITE_ENDPOINT, [
    216                 'timeout' => 30,
    217                 'headers' => [
    218                     'Content-Type' => 'application/json',
    219                     'Accept' => 'application/json',
    220                 ],
    221                 'body' => wp_json_encode($site_data)
    222             ]);
    223 
    224             if (is_wp_error($link_response)) {
    225                 throw new \RuntimeException('Failed to link site: ' . $link_response->get_error_message());
    226             }
    227 
    228             $link_status = wp_remote_retrieve_response_code($link_response);
    229             $link_body = wp_remote_retrieve_body($link_response);
    230 
    231            
    232 
    233             if ($link_status === 409) {
    234                 update_option(self::API_KEY_OPTION, $api_key);
    235                 wp_send_json_success(sprintf('Site already connected with %s Portal', $display_name));
    236                 return;
    237             }
    238 
    239             if ($link_status !== 200) {
    240                 throw new \RuntimeException('Failed to link site. Please try again or contact support.');
    241             }
    242 
    243             update_option(self::API_KEY_OPTION, $api_key);
    244207            wp_send_json_success(sprintf('Valid API Key - Site Successfully Linked with %s Portal', $display_name));
    245208
    … …  
    248211            wp_send_json_error($e->getMessage());
    249212        }
     213    }
     214
     215    /**
     216     * Register (or re-register) this WordPress site with the SiteSkite portal.
     217     *
     218     * Used after Save API Key and after activation when a restored DB already
     219     * contains siteskite_api_key (backup → sandbox staging flow).
     220     *
     221     * @return true|\WP_Error
     222     */
     223    public function register_site_with_portal(string $api_key) {
     224        $api_key = trim($api_key);
     225        if ($api_key === '') {
     226            return new \WP_Error('missing_api_key', 'API key is required');
     227        }
     228
     229        $site_url = get_site_url();
     230        $parsed_url = wp_parse_url($site_url);
     231        $host = $parsed_url['host'] ?? '';
     232        $path = isset($parsed_url['path']) ? rtrim($parsed_url['path'], '/') : '';
     233        $domain = $host . ($path ? $path : '');
     234
     235        if ($domain === '') {
     236            return new \WP_Error('missing_domain', 'Could not determine site domain');
     237        }
     238
     239        $site_data = [
     240            'name' => get_bloginfo('name'),
     241            'domain' => $domain,
     242            'status' => '1',
     243            'php_version' => PHP_VERSION,
     244            'wp_version' => get_bloginfo('version'),
     245            'token' => $api_key,
     246        ];
     247        $site_data = array_merge($site_data, Utils::get_rest_connectivity());
     248
     249        $link_response = wp_remote_post(self::LINK_SITE_ENDPOINT, [
     250            'timeout' => 30,
     251            'headers' => [
     252                'Content-Type' => 'application/json',
     253                'Accept' => 'application/json',
     254            ],
     255            'body' => wp_json_encode($site_data),
     256        ]);
     257
     258        if (is_wp_error($link_response)) {
     259            $this->logger->error('Portal site registration failed: ' . $link_response->get_error_message(), [
     260                'domain' => $domain,
     261            ]);
     262            return $link_response;
     263        }
     264
     265        $link_status = (int) wp_remote_retrieve_response_code($link_response);
     266
     267        // 409 = domain already connected for this account — treat as success.
     268        if ($link_status !== 200 && $link_status !== 409) {
     269            $this->logger->error('Portal site registration rejected', [
     270                'domain' => $domain,
     271                'status' => $link_status,
     272                'body' => (string) wp_remote_retrieve_body($link_response),
     273            ]);
     274            return new \WP_Error(
     275                'link_failed',
     276                'Failed to link site. Please try again or contact support.',
     277                ['status' => $link_status]
     278            );
     279        }
     280
     281        update_option(self::API_KEY_OPTION, $api_key);
     282        $this->logger->info('Portal site registration succeeded', [
     283            'domain' => $domain,
     284            'status' => $link_status,
     285        ]);
     286
     287        return true;
    250288    }
    251289
  • siteskite/trunk/includes/Backup/BackupManager.php

    r3797113 r3808895  
    627627                "SiteSkite Process {$type} Backup"
    628628            );
     629
     630            // Temporary resume safety net: only while this backup is pending; deleted on finish.
     631            $this->ensure_backup_resume_safety_net($backup_id);
    629632
    630633            // Send initial notification
    … …  
    40474050    }
    40484051
     4052    /** Delay before the one-shot resume safety net fires. */
     4053    private const RESUME_SAFETY_NET_DELAY_SECONDS = 1200; // 20 minutes
     4054
     4055    /** If updated_at is older than this, treat continue chain as stuck and poke it. */
     4056    private const RESUME_STALE_SECONDS = 600; // 10 minutes
     4057
     4058    /**
     4059     * Schedule a one-shot external cron safety net for an in-progress backup.
     4060     * Exists only while the backup is pending; not a permanent site-wide cron.
     4061     *
     4062     * @param bool $force Delete + recreate (used after a safety-net fire so the next check is scheduled)
     4063     */
     4064    public function ensure_backup_resume_safety_net(string $backup_id, bool $force = false): void
     4065    {
     4066        if ($backup_id === '' || !$this->external_cron_manager || !$this->external_cron_manager->is_enabled()) {
     4067            return;
     4068        }
     4069
     4070        $action = ExternalCronManager::ACTION_BACKUP_RESUME_SAFETY_NET;
     4071        $args = [$backup_id];
     4072        $existing = $this->external_cron_manager->get_job_id_by_action($action, $args);
     4073
     4074        if ($existing && !$force) {
     4075            return;
     4076        }
     4077
     4078        if ($existing && $force) {
     4079            $this->external_cron_manager->delete_job($existing);
     4080        }
     4081
     4082        $job_id = $this->external_cron_manager->schedule_single_event(
     4083            $action,
     4084            $args,
     4085            self::RESUME_SAFETY_NET_DELAY_SECONDS,
     4086            'SiteSkite: Backup Resume Safety Net'
     4087        );
     4088
     4089        if ($job_id) {
     4090            $this->logger->info('Scheduled backup resume safety net', [
     4091                'backup_id' => $backup_id,
     4092                'job_id' => $job_id,
     4093                'delay_seconds' => self::RESUME_SAFETY_NET_DELAY_SECONDS,
     4094                'forced' => $force,
     4095            ]);
     4096        }
     4097    }
     4098
     4099    /**
     4100     * Remove the resume safety net for a backup (complete / fail / cancel).
     4101     */
     4102    public function clear_backup_resume_safety_net(string $backup_id): void
     4103    {
     4104        if ($backup_id === '' || !$this->external_cron_manager || !$this->external_cron_manager->is_enabled()) {
     4105            return;
     4106        }
     4107
     4108        $action = ExternalCronManager::ACTION_BACKUP_RESUME_SAFETY_NET;
     4109        $args = [$backup_id];
     4110        $job_id = $this->external_cron_manager->get_job_id_by_action($action, $args);
     4111        if ($job_id) {
     4112            $this->external_cron_manager->delete_job($job_id);
     4113            $this->logger->debug('Cleared backup resume safety net', [
     4114                'backup_id' => $backup_id,
     4115                'job_id' => $job_id,
     4116            ]);
     4117        }
     4118    }
     4119
     4120    /**
     4121     * Ensure every incomplete backup has a temporary resume safety net (for upgraded installs).
     4122     */
     4123    public function ensure_safety_nets_for_incomplete_backups(): void
     4124    {
     4125        global $wpdb;
     4126        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     4127        $option_names = $wpdb->get_col(
     4128            "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'siteskite_backup_%'"
     4129        );
     4130        if (!is_array($option_names)) {
     4131            return;
     4132        }
     4133
     4134        foreach ($option_names as $option_name) {
     4135            $option_name = (string) $option_name;
     4136            if (!preg_match('/^siteskite_backup_((?:siteskite_backup_|skte_backup_)?[a-zA-Z0-9]+(?:_incremental)?)$/', $option_name, $m)) {
     4137                continue;
     4138            }
     4139            $data = get_option($option_name);
     4140            if (!is_array($data)) {
     4141                continue;
     4142            }
     4143            $status = (string) ($data['status'] ?? '');
     4144            if (!in_array($status, ['initializing', 'processing', 'uploading', 'pending'], true)) {
     4145                continue;
     4146            }
     4147            $this->ensure_backup_resume_safety_net($m[1]);
     4148        }
     4149    }
     4150
     4151    /**
     4152     * Safety-net handler: if this backup is still unfinished and quiet, recreate continue work.
     4153     *
     4154     * @return array{status: string, backup_id: string, reschedule_safety_net?: bool, resumed?: bool, reason?: string}
     4155     */
     4156    public function handle_backup_resume_safety_net(string $backup_id): array
     4157    {
     4158        $backup_id = (string) $backup_id;
     4159        $result = [
     4160            'status' => 'skipped',
     4161            'backup_id' => $backup_id,
     4162            'reschedule_safety_net' => false,
     4163            'resumed' => false,
     4164        ];
     4165
     4166        $backup_info = get_option(self::OPTION_PREFIX . $backup_id);
     4167        if (!is_array($backup_info) || $backup_info === []) {
     4168            $result['reason'] = 'backup_not_found';
     4169            return $result;
     4170        }
     4171
     4172        $status = (string) ($backup_info['status'] ?? '');
     4173        if (in_array($status, ['completed', 'failed', 'cancelled'], true)) {
     4174            $this->clear_backup_resume_safety_net($backup_id);
     4175            $result['reason'] = 'backup_finished_' . $status;
     4176            return $result;
     4177        }
     4178
     4179        if (!in_array($status, ['initializing', 'processing', 'uploading', 'pending'], true)) {
     4180            $result['reason'] = 'status_not_resumable_' . $status;
     4181            return $result;
     4182        }
     4183
     4184        // Still unfinished → keep a future safety net (created after this one-shot job is deleted).
     4185        $result['reschedule_safety_net'] = true;
     4186
     4187        $updated_at = (int) ($backup_info['updated_at'] ?? $backup_info['started_at'] ?? $backup_info['created_at'] ?? 0);
     4188        $age = $updated_at > 0 ? (time() - $updated_at) : self::RESUME_STALE_SECONDS + 1;
     4189
     4190        if ($age < self::RESUME_STALE_SECONDS) {
     4191            $result['status'] = 'active';
     4192            $result['reason'] = 'recently_updated';
     4193            return $result;
     4194        }
     4195
     4196        $this->logger->warning('Backup resume safety net: continue chain looks stuck, attempting resume', [
     4197            'backup_id' => $backup_id,
     4198            'status' => $status,
     4199            'quiet_seconds' => $age,
     4200            'type' => $backup_info['type'] ?? '',
     4201        ]);
     4202
     4203        $this->resume_incomplete_backup($backup_id, $backup_info);
     4204        $result['status'] = 'resumed';
     4205        $result['resumed'] = true;
     4206        $result['reason'] = 'stale_continue_resumed';
     4207
     4208        return $result;
     4209    }
     4210
     4211    /**
     4212     * Recreate / poke the correct continue path for an incomplete backup.
     4213     *
     4214     * @param array<string, mixed> $backup_info
     4215     */
     4216    private function resume_incomplete_backup(string $backup_id, array $backup_info): void
     4217    {
     4218        $callback_url = $backup_info['callback_url'] ?? get_option(SITESKITE_OPTION_PREFIX . 'callback_url');
     4219        $callback_url = is_string($callback_url) ? $callback_url : null;
     4220        $type = (string) ($backup_info['type'] ?? 'full');
     4221        $status = (string) ($backup_info['status'] ?? '');
     4222        $incremental = !empty($backup_info['incremental_mode']) || strpos($backup_id, '_incremental') !== false;
     4223
     4224        // Clear "already scheduled" flags so handlers can recreate missing external jobs.
     4225        if (!empty($backup_info['cron_job_scheduled_db'])) {
     4226            $backup_info['cron_job_scheduled_db'] = false;
     4227            update_option(self::OPTION_PREFIX . $backup_id, $backup_info);
     4228        }
     4229        if (!empty($backup_info['cron_job_scheduled_files'])) {
     4230            $backup_info['cron_job_scheduled_files'] = false;
     4231            update_option(self::OPTION_PREFIX . $backup_id, $backup_info);
     4232        }
     4233
     4234        if ($incremental) {
     4235            $this->schedule_cron_event('siteskite_incremental_continue', [$backup_id], 60, 'SiteSkite Incremental Continue');
     4236            $this->handle_incremental_continue($backup_id);
     4237            return;
     4238        }
     4239
     4240        if ($status === 'uploading'
     4241            || get_transient('siteskite_classic_chunked_meta_' . $backup_id)
     4242            || get_transient('siteskite_b2_lf_' . $backup_id)
     4243            || get_transient('siteskite_dropbox_ul_' . $backup_id)
     4244            || get_transient('siteskite_gdrive_ul_' . $backup_id)
     4245            || get_transient('siteskite_s3_mpu_' . $backup_id)
     4246        ) {
     4247            $this->schedule_cron_event(
     4248                self::CLASSIC_LARGE_UPLOAD_CRON_HOOK,
     4249                [$backup_id],
     4250                0,
     4251                'SiteSkite Classic Large Upload Continue'
     4252            );
     4253            $this->continue_classic_large_upload($backup_id);
     4254            return;
     4255        }
     4256
     4257        if ($type === 'database') {
     4258            $this->handle_database_backup_cron($backup_id, $callback_url);
     4259            return;
     4260        }
     4261
     4262        if ($type === 'files') {
     4263            $this->handle_files_backup_cron($backup_id, $callback_url);
     4264            return;
     4265        }
     4266
     4267        // full: resume whichever stage is still open
     4268        $db_done = !empty($backup_info['db_backup_complete']);
     4269        $files_done = !empty($backup_info['files_backup_complete']);
     4270        if (!$db_done) {
     4271            $this->handle_database_backup_cron($backup_id, $callback_url);
     4272            return;
     4273        }
     4274        if (!$files_done) {
     4275            $this->handle_files_backup_cron($backup_id, $callback_url);
     4276            return;
     4277        }
     4278
     4279        $this->handle_full_backup_final_zip_cron($backup_id, $callback_url);
     4280    }
     4281
    40494282    /**
    40504283     * Delay local ZIP cleanup while classic backup may still need the ZIP on disk for cloud upload.
    … …  
    998510218        update_option(self::OPTION_PREFIX . $backup_id, $backup_info);
    998610219
     10220        $this->clear_backup_resume_safety_net($backup_id);
     10221
    998710222        // Trigger cleanup immediately (instead of scheduling it)
    998810223        $this->logger->info('Triggering immediate cleanup for cancelled incremental backup', [
    … …  
    1004510280            $cron_actions[] = 'process_full_backup_final_zip_cron';
    1004610281        }
     10282        $cron_actions[] = ExternalCronManager::ACTION_BACKUP_RESUME_SAFETY_NET;
    1004710283
    1004810284        // Delete external cron jobs for each action
  • siteskite/trunk/includes/Cleanup/CleanupManager.php

    r3534022 r3808895  
    44namespace SiteSkite\Cleanup;
    55
     6use SiteSkite\Cron\ExternalCronManager;
    67use SiteSkite\Logger\Logger;
    7 use SiteSkite\Backup\BackupManager;
    88use SiteSkite\Core\Utils;
    99use function get_option;
     10use function update_option;
     11use function set_transient;
     12use function get_transient;
    1013use function wp_upload_dir;
    1114use function wp_delete_file;
    … …  
    1720use function delete_transient;
    1821use function WP_Filesystem;
     22use function time;
     23use function is_array;
     24use function is_dir;
     25use function is_file;
     26use function file_exists;
     27use function filemtime;
     28use function scandir;
    1929use const DAY_IN_SECONDS;
    20 use const SITESKITE_BACKUP_DIR;
     30use const HOUR_IN_SECONDS;
    2131use const ABSPATH;
    2232
    … …  
    2535 */
    2636class CleanupManager {
     37    public const SCAVENGER_ACTION = 'siteskite_scavenge_stale_backups';
     38
     39    /** Abandoned in-progress backups older than this are reaped. */
     40    private const STALE_IN_PROGRESS_SECONDS = 24 * HOUR_IN_SECONDS;
     41
     42    /**
     43     * A processing/uploading backup is treated as still alive only if updated
     44     * within this window (continue cron is every minute). Older rows must not
     45     * block a full workspace wipe after a successful backup.
     46     */
     47    private const ACTIVE_HEARTBEAT_SECONDS = 2 * HOUR_IN_SECONDS;
     48
     49    /** Completed leftovers whose cleanup cron never ran. */
     50    private const STALE_COMPLETED_SECONDS = HOUR_IN_SECONDS;
     51
     52    /** Throttle piggyback scavenger runs. */
     53    private const SCAVENGE_THROTTLE_TRANSIENT = 'siteskite_scavenge_throttle';
     54    private const SCAVENGE_THROTTLE_SECONDS = 6 * HOUR_IN_SECONDS;
     55
     56    private const SCAVENGER_ENSURED_OPTION = 'siteskite_scavenger_cron_ensured';
     57
    2758    /**
    2859     * @var Logger Logger instance
    … …  
    3162
    3263    /**
     64     * @var ExternalCronManager|null
     65     */
     66    private ?ExternalCronManager $external_cron_manager = null;
     67
     68    /**
    3369     * @var string Backup directory path
    3470     */
    … …  
    4379     * Constructor
    4480     */
    45     public function __construct(Logger $logger) {
     81    public function __construct(Logger $logger, ?ExternalCronManager $external_cron_manager = null) {
    4682        $this->logger = $logger;
     83        $this->external_cron_manager = $external_cron_manager;
    4784        $this->init_directories();
    48        
    49         // Register cleanup hooks
     85
    5086        add_action('siteskite_cleanup_backup_files', [$this, 'cleanup_backup'], 10, 1);
     87        add_action(self::SCAVENGER_ACTION, [$this, 'scavenge_stale_backups'], 10, 0);
     88    }
     89
     90    /**
     91     * Allow Plugin bootstrap to inject ExternalCronManager after construction if needed.
     92     */
     93    public function set_external_cron_manager(ExternalCronManager $external_cron_manager): void
     94    {
     95        $this->external_cron_manager = $external_cron_manager;
     96    }
     97
     98    /**
     99     * Register a daily external cron scavenger once (safe for already-scheduled sites).
     100     * Does not touch existing backup schedules.
     101     */
     102    public function ensure_scavenger_cron(): void
     103    {
     104        if (!$this->external_cron_manager) {
     105            return;
     106        }
     107
     108        $existing = $this->external_cron_manager->get_job_id_by_action(self::SCAVENGER_ACTION, []);
     109        if ($existing) {
     110            if (!get_option(self::SCAVENGER_ENSURED_OPTION)) {
     111                update_option(self::SCAVENGER_ENSURED_OPTION, 1, false);
     112            }
     113            return;
     114        }
     115
     116        // Already tried recently and job still missing — avoid API spam on every request.
     117        if (get_transient('siteskite_scavenger_ensure_attempt')) {
     118            return;
     119        }
     120        set_transient('siteskite_scavenger_ensure_attempt', 1, 12 * HOUR_IN_SECONDS);
     121
     122        if (!$this->external_cron_manager->is_enabled()) {
     123            return;
     124        }
     125
     126        $job_id = $this->external_cron_manager->create_recurring_job(
     127            self::SCAVENGER_ACTION,
     128            [],
     129            'daily',
     130            ['time' => '04:15'],
     131            'SiteSkite: Stale Backup Scavenger'
     132        );
     133
     134        if ($job_id) {
     135            update_option(self::SCAVENGER_ENSURED_OPTION, 1, false);
     136            $this->logger->info('Registered daily stale backup scavenger cron', [
     137                'job_id' => $job_id,
     138            ]);
     139        }
    51140    }
    52141
    … …  
    293382
    294383    /**
    295      * Clean up failed backups
     384     * Clean up failed backups (partial *.part crumbs)
    296385     */
    297386    public function cleanup_failed_backups(): void {
    298387        try {
    299             $partial_files = glob(SITESKITE_BACKUP_DIR . '/*.part');
     388            $partial_files = glob($this->backup_dir . '/*.part');
    300389            if (!$partial_files) {
    301390                return;
    … …  
    303392
    304393            foreach ($partial_files as $file) {
    305                 if (filemtime($file) < time() - 3600) { // Partial files older than 1 hour
     394                if (filemtime($file) < time() - 3600) {
    306395                    if (wp_delete_file($file)) {
    307396                        $this->logger->info('Deleted failed backup file: ' . basename($file));
    … …  
    317406
    318407    /**
    319      * Clean up backup files and logs
    320      */
    321    
     408     * Clean up one backup's database references, then wipe leftover local garbage.
     409     *
     410     * When no other backup is actively running, empties the entire SiteSkite backups
     411     * folder (zips, manifests, locks, chunks, etc.) plus SiteSkite logs — "one for all".
     412     * If another backup is still active, only removes this backup_id's files.
     413     */
    322414    public function cleanup_backup(string $backup_id): void
    323415    {
    … …  
    327419            ]);
    328420
    329             // Clean up backup files (try each backup_id shape used in filenames)
    330             foreach (Utils::backup_id_option_variants($backup_id) as $id_variant) {
    331                 $backup_files = [
    332                     $this->backup_dir . '/' . $id_variant . '_db.zip',
    333                     $this->backup_dir . '/' . $id_variant . '_files.zip',
    334                     $this->backup_dir . '/' . $id_variant . '_full.zip',
    335                 ];
    336 
    337                 foreach ($backup_files as $file) {
    338                     if (file_exists($file)) {
    339                         wp_delete_file($file);
    340                         $this->logger->debug('Removed backup file', [
    341                             'file' => basename($file),
    342                         ]);
    343                     }
    344                 }
    345 
    346                 $manifest_files = glob($this->backup_dir . '/' . $id_variant . '_*.manifest');
    347                 if ($manifest_files) {
    348                     foreach ($manifest_files as $manifest_file) {
    349                         if (file_exists($manifest_file) && wp_delete_file($manifest_file)) {
    350                             $this->logger->debug('Removed manifest file', [
    351                                 'file' => basename($manifest_file),
    352                             ]);
    353                         }
    354                     }
    355                 }
    356             }
    357 
    358             // Any legacy/per-backup-named logs under the real SiteSkite logs directory (Logger uses daily siteskite-*.log names)
    359             $log_pattern = $this->logs_dir . '/*' . $backup_id . '*.log';
    360 
    361             foreach (glob($log_pattern) ?: [] as $log_file) {
    362                 if (is_file($log_file)) {
    363                     wp_delete_file($log_file);
    364                     $this->logger->debug('Removed log file', [
    365                         'file' => basename($log_file)
    366                     ]);
    367                 }
    368             }
    369 
    370             // Clean up all database references (both bare and double-prefixed option keys)
    371             $deleted_options = Utils::delete_per_backup_options($backup_id);
    372             Utils::delete_per_backup_transients($backup_id);
    373 
    374             // Hybrid cron + pending-upload options (hash keys; match any backup_id variant)
    375             global $wpdb;
    376             $hybrid_cron_pattern = 'siteskite_hybrid_cron_%';
    377             // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    378             $hybrid_cron_options = $wpdb->get_col($wpdb->prepare(
    379                 "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
    380                 $hybrid_cron_pattern
    381             ));
    382 
    383             foreach ($hybrid_cron_options as $option_name) {
    384                 foreach (Utils::backup_id_option_variants($backup_id) as $id_variant) {
    385                     $option_value = get_option($option_name);
    386                     if (is_array($option_value)
    387                         && isset($option_value['backup_id'])
    388                         && $option_value['backup_id'] === $id_variant
    389                     ) {
    390                         if (delete_option($option_name)) {
    391                             $deleted_options[] = $option_name;
    392                         }
    393                         break;
    394                     }
    395                     if (strpos($option_name, $id_variant) !== false) {
    396                         if (delete_option($option_name)) {
    397                             $deleted_options[] = $option_name;
    398                         }
    399                         break;
    400                     }
    401                 }
    402             }
    403 
    404             $pending_prefix = \defined('SITESKITE_OPTION_PREFIX') ? \constant('SITESKITE_OPTION_PREFIX') : 'siteskite_';
    405             foreach (Utils::backup_id_option_variants($backup_id) as $id_variant) {
    406                 $pending_upload_like = $wpdb->esc_like($pending_prefix . 'pending_upload_' . $id_variant . '_') . '%';
    407                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    408                 $pending_upload_options = $wpdb->get_col($wpdb->prepare(
    409                     "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
    410                     $pending_upload_like
    411                 ));
    412                 foreach ($pending_upload_options as $pending_opt) {
    413                     if (delete_option($pending_opt)) {
    414                         $deleted_options[] = $pending_opt;
    415                     }
    416                 }
    417             }
    418 
    419             // Clean up lock files if they still exist (try each backup_id shape used in filenames)
    420             $lock_files = [];
    421             foreach (Utils::backup_id_option_variants($backup_id) as $id_variant) {
    422                 $lock_files[] = $this->backup_dir . '/' . $id_variant . '_db.lock';
    423                 $lock_files[] = $this->backup_dir . '/' . $id_variant . '_files.lock';
    424             }
    425             foreach ($lock_files as $lock_file) {
    426                 if (file_exists($lock_file)) {
    427                     @unlink($lock_file);
    428                     $this->logger->debug('Removed lock file', [
    429                         'file' => basename($lock_file)
    430                     ]);
    431                 }
    432             }
    433            
    434             if (!empty($deleted_options)) {
    435                 $this->logger->info('Cleaned up database references for backup', [
    436                     'backup_id' => $backup_id,
    437                     'deleted_options' => $deleted_options,
    438                     'deleted_count' => count($deleted_options)
    439                 ]);
    440             }
    441 
    442             // Logger writes siteskite-YYYY-MM-DD.log (no backup_id in filename). Match prior cleanup_all behavior for this hook.
    443             $logs_removed = $this->cleanup_log_files();
    444             if ($logs_removed > 0) {
    445                 $this->logger->info('Removed SiteSkite log files during backup cleanup', [
    446                     'backup_id' => $backup_id,
    447                     'logs_removed' => $logs_removed,
    448                 ]);
    449             }
    450        
     421            $this->cleanup_backup_database_references($backup_id);
     422            $this->cleanup_backup_id_files($backup_id);
     423
     424            // Double-guard success path: after this backup is done, clear the whole folder
     425            // when safe so no stranded zip/package/logs remain for completed work.
     426            if (!$this->has_active_backup($backup_id)) {
     427                $this->wipe_backup_workspace('post_cleanup_backup:' . $backup_id);
     428                $this->cleanup_all_stranded_backup_options();
     429            }
     430
     431            $this->cleanup_failed_backups();
     432            $this->cleanup_temp_files();
     433
    451434        } catch (\Exception $e) {
    452435            $this->logger->error('Failed to cleanup backup', [
    … …  
    454437                'error' => $e->getMessage()
    455438            ]);
     439        }
     440    }
     441
     442    /**
     443     * Find abandoned / leftover backups and finish cleanup (DB + folder).
     444     * Safe to call from daily external cron or as a throttled piggyback.
     445     *
     446     * @param bool $force Skip throttle (used by dedicated scavenger cron)
     447     * @return array{cleaned: list<string>, wiped_workspace: bool, skipped: bool}
     448     */
     449    public function scavenge_stale_backups(bool $force = true): array
     450    {
     451        $result = [
     452            'cleaned' => [],
     453            'wiped_workspace' => false,
     454            'skipped' => false,
     455        ];
     456
     457        if (!$force && get_transient(self::SCAVENGE_THROTTLE_TRANSIENT)) {
     458            $result['skipped'] = true;
     459            return $result;
     460        }
     461
     462        try {
     463            $this->logger->info('Starting stale backup scavenger');
     464
     465            $stale_ids = $this->find_stale_backup_ids();
     466            foreach ($stale_ids as $backup_id) {
     467                $this->logger->info('Scavenger cleaning stale backup', [
     468                    'backup_id' => $backup_id,
     469                ]);
     470                $this->cleanup_backup($backup_id);
     471                $result['cleaned'][] = $backup_id;
     472            }
     473
     474            if (!$this->has_active_backup()) {
     475                $this->wipe_backup_workspace('scavenger');
     476                // Final DB sweep: any leftover backup/progress option rows (both
     477                // siteskite_backup_* and legacy skte_backup_* id shapes).
     478                $this->cleanup_all_stranded_backup_options();
     479                $result['wiped_workspace'] = true;
     480            } else {
     481                $this->cleanup_orphan_classic_packages();
     482                $this->cleanup_orphan_progress_options();
     483                $this->cleanup_failed_backups();
     484                $this->cleanup_temp_files();
     485            }
     486
     487            set_transient(self::SCAVENGE_THROTTLE_TRANSIENT, 1, self::SCAVENGE_THROTTLE_SECONDS);
     488
     489            $this->logger->info('Stale backup scavenger finished', $result);
     490        } catch (\Exception $e) {
     491            $this->logger->error('Stale backup scavenger failed', [
     492                'error' => $e->getMessage(),
     493            ]);
     494        }
     495
     496        return $result;
     497    }
     498
     499    /**
     500     * Throttled scavenger for piggyback on existing cron hits (scheduled backup, etc.).
     501     *
     502     * @return array{cleaned: list<string>, wiped_workspace: bool, skipped: bool}
     503     */
     504    public function maybe_scavenge_stale_backups(): array
     505    {
     506        return $this->scavenge_stale_backups(false);
     507    }
     508
     509    /**
     510     * Per-backup option name pattern for both current and legacy id shapes:
     511     * - siteskite_backup_siteskite_backup_{hex}
     512     * - siteskite_backup_skte_backup_{hex}
     513     * - siteskite_progress_siteskite_backup_{hex}
     514     * - siteskite_progress_skte_backup_{hex}
     515     */
     516    private const BACKUP_RECORD_OPTION_REGEX = '/^siteskite_(?:backup|progress)_((?:siteskite_backup_|skte_backup_)?[a-zA-Z0-9]+(?:_incremental)?)$/';
     517
     518    /**
     519     * @return list<string>
     520     */
     521    private function find_stale_backup_ids(): array
     522    {
     523        global $wpdb;
     524        $stale = [];
     525        $now = time();
     526
     527        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     528        $option_names = $wpdb->get_col(
     529            "SELECT option_name FROM {$wpdb->options}
     530             WHERE option_name LIKE 'siteskite_backup_%'
     531                OR option_name LIKE 'siteskite_progress_%'"
     532        );
     533
     534        if (!is_array($option_names)) {
     535            return [];
     536        }
     537
     538        $seen = [];
     539
     540        foreach ($option_names as $option_name) {
     541            $option_name = (string) $option_name;
     542            $backup_id = $this->extract_backup_id_from_option_name($option_name);
     543            if ($backup_id === '' || isset($seen[$backup_id])) {
     544                continue;
     545            }
     546
     547            // Progress-only orphan (no matching backup option) → always stale.
     548            if (str_starts_with($option_name, 'siteskite_progress_')) {
     549                $has_backup_row = false;
     550                foreach (Utils::backup_id_option_variants($backup_id) as $variant) {
     551                    if (get_option('siteskite_backup_' . $variant) !== false) {
     552                        $has_backup_row = true;
     553                        break;
     554                    }
     555                }
     556                if (!$has_backup_row) {
     557                    $seen[$backup_id] = true;
     558                    $stale[] = $backup_id;
     559                    continue;
     560                }
     561                // Progress row with a live backup row: decide via the backup record below.
     562                continue;
     563            }
     564
     565            $data = get_option($option_name);
     566            if (!is_array($data)) {
     567                $seen[$backup_id] = true;
     568                $stale[] = $backup_id;
     569                continue;
     570            }
     571
     572            $status = (string) ($data['status'] ?? '');
     573            $updated_at = (int) ($data['updated_at'] ?? $data['created_at'] ?? 0);
     574            $age = $updated_at > 0 ? ($now - $updated_at) : self::STALE_IN_PROGRESS_SECONDS + 1;
     575
     576            $is_stale = false;
     577            if (in_array($status, ['failed', 'cancelled'], true)) {
     578                $is_stale = true;
     579            } elseif ($status === 'completed' && $age >= self::STALE_COMPLETED_SECONDS) {
     580                $is_stale = true;
     581            } elseif (in_array($status, ['processing', 'uploading', 'pending', ''], true)
     582                && $age >= self::STALE_IN_PROGRESS_SECONDS
     583            ) {
     584                $is_stale = true;
     585            }
     586
     587            if ($is_stale) {
     588                $seen[$backup_id] = true;
     589                $stale[] = $backup_id;
     590            }
     591        }
     592
     593        return $stale;
     594    }
     595
     596    /**
     597     * Extract backup_id from siteskite_backup_* / siteskite_progress_* option names.
     598     */
     599    private function extract_backup_id_from_option_name(string $option_name): string
     600    {
     601        if (preg_match(self::BACKUP_RECORD_OPTION_REGEX, $option_name, $m)) {
     602            return $m[1];
     603        }
     604        return '';
     605    }
     606
     607    /**
     608     * True if any backup (other than $except_backup_id) looks actively in progress.
     609     */
     610    public function has_active_backup(?string $except_backup_id = null): bool
     611    {
     612        global $wpdb;
     613        $now = time();
     614        $except_variants = $except_backup_id ? Utils::backup_id_option_variants($except_backup_id) : [];
     615
     616        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     617        $option_names = $wpdb->get_col(
     618            "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'siteskite_backup_%'"
     619        );
     620
     621        if (!is_array($option_names)) {
     622            return false;
     623        }
     624
     625        foreach ($option_names as $option_name) {
     626            $option_name = (string) $option_name;
     627            if (!preg_match('/^siteskite_backup_[a-zA-Z0-9_]+$/', $option_name)) {
     628                continue;
     629            }
     630
     631            $id_part = substr($option_name, strlen('siteskite_backup_'));
     632            if ($except_variants && in_array($id_part, $except_variants, true)) {
     633                continue;
     634            }
     635            // Also skip when except is the full option key shape
     636            if ($except_backup_id && (
     637                $option_name === 'siteskite_backup_' . $except_backup_id
     638                || $id_part === $except_backup_id
     639            )) {
     640                continue;
     641            }
     642
     643            $data = get_option($option_name);
     644            if (!is_array($data)) {
     645                continue;
     646            }
     647
     648            $status = (string) ($data['status'] ?? '');
     649            if (!in_array($status, ['processing', 'uploading', 'pending'], true)) {
     650                continue;
     651            }
     652
     653            $updated_at = (int) ($data['updated_at'] ?? $data['created_at'] ?? 0);
     654            if ($updated_at > 0 && ($now - $updated_at) < self::ACTIVE_HEARTBEAT_SECONDS) {
     655                return true;
     656            }
     657        }
     658
     659        return false;
     660    }
     661
     662    /**
     663     * Empty backups folder + SiteSkite logs using wp_delete_file / WP_Filesystem.
     664     */
     665    public function wipe_backup_workspace(string $reason = ''): void
     666    {
     667        $this->logger->info('Wiping SiteSkite backup workspace', [
     668            'reason' => $reason,
     669            'backup_dir' => $this->backup_dir,
     670        ]);
     671
     672        $files_removed = $this->cleanup_all_backup_files();
     673        $manifests_removed = $this->cleanup_classic_manifest_files();
     674        $logs_removed = $this->cleanup_log_files();
     675        $this->cleanup_old_manifests();
     676
     677        $this->logger->info('Backup workspace wipe completed', [
     678            'reason' => $reason,
     679            'files_removed' => $files_removed,
     680            'manifests_removed' => $manifests_removed,
     681            'logs_removed' => $logs_removed,
     682        ]);
     683    }
     684
     685    /**
     686     * Delete all stranded per-backup DB rows (backup + progress) when no job is active.
     687     * Covers current siteskite_backup_* and legacy skte_backup_* id shapes from screenshots.
     688     *
     689     * @return list<string> Deleted option names
     690     */
     691    private function cleanup_all_stranded_backup_options(): array
     692    {
     693        global $wpdb;
     694        $deleted = [];
     695
     696        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     697        $option_names = $wpdb->get_col(
     698            "SELECT option_name FROM {$wpdb->options}
     699             WHERE option_name LIKE 'siteskite_backup_%'
     700                OR option_name LIKE 'siteskite_progress_%'"
     701        );
     702
     703        if (!is_array($option_names)) {
     704            return [];
     705        }
     706
     707        $backup_ids = [];
     708        foreach ($option_names as $option_name) {
     709            $backup_id = $this->extract_backup_id_from_option_name((string) $option_name);
     710            if ($backup_id !== '') {
     711                $backup_ids[$backup_id] = true;
     712            }
     713        }
     714
     715        foreach (array_keys($backup_ids) as $backup_id) {
     716            // Skip anything still actively heartbeating.
     717            if ($this->is_backup_id_actively_running($backup_id)) {
     718                continue;
     719            }
     720            $removed = $this->cleanup_backup_database_references($backup_id);
     721            foreach ($removed as $name) {
     722                $deleted[] = $name;
     723            }
     724        }
     725
     726        if ($deleted !== []) {
     727            $this->logger->info('Removed stranded backup/progress database options', [
     728                'deleted_count' => count($deleted),
     729                'deleted_options' => $deleted,
     730            ]);
     731        }
     732
     733        return $deleted;
     734    }
     735
     736    /**
     737     * Remove progress options whose matching backup record is already gone.
     738     */
     739    private function cleanup_orphan_progress_options(): void
     740    {
     741        global $wpdb;
     742
     743        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     744        $progress_names = $wpdb->get_col(
     745            "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'siteskite_progress_%'"
     746        );
     747
     748        if (!is_array($progress_names)) {
     749            return;
     750        }
     751
     752        foreach ($progress_names as $option_name) {
     753            $option_name = (string) $option_name;
     754            $backup_id = $this->extract_backup_id_from_option_name($option_name);
     755            if ($backup_id === '') {
     756                continue;
     757            }
     758
     759            $has_backup_row = false;
     760            foreach (Utils::backup_id_option_variants($backup_id) as $variant) {
     761                if (get_option('siteskite_backup_' . $variant) !== false) {
     762                    $has_backup_row = true;
     763                    break;
     764                }
     765            }
     766
     767            if ($has_backup_row || $this->is_backup_id_actively_running($backup_id)) {
     768                continue;
     769            }
     770
     771            if (delete_option($option_name)) {
     772                $this->logger->debug('Removed orphan progress option', [
     773                    'option' => $option_name,
     774                ]);
     775            }
     776            // Also clear related keys for this id (uploaded flags, etc.)
     777            $this->cleanup_backup_database_references($backup_id);
     778        }
     779    }
     780
     781    /**
     782     * Whether a specific backup_id still looks actively in progress.
     783     */
     784    private function is_backup_id_actively_running(string $backup_id): bool
     785    {
     786        $now = time();
     787        foreach (Utils::backup_id_option_variants($backup_id) as $variant) {
     788            $data = get_option('siteskite_backup_' . $variant);
     789            if (!is_array($data)) {
     790                continue;
     791            }
     792            $status = (string) ($data['status'] ?? '');
     793            if (!in_array($status, ['processing', 'uploading', 'pending'], true)) {
     794                continue;
     795            }
     796            $updated_at = (int) ($data['updated_at'] ?? $data['created_at'] ?? 0);
     797            if ($updated_at > 0 && ($now - $updated_at) < self::ACTIVE_HEARTBEAT_SECONDS) {
     798                return true;
     799            }
     800        }
     801        return false;
     802    }
     803
     804    /**
     805     * Remove classic zip/manifest/lock packages that no longer have a live backup option.
     806     */
     807    private function cleanup_orphan_classic_packages(): void
     808    {
     809        if (!is_dir($this->backup_dir)) {
     810            return;
     811        }
     812
     813        $patterns = [
     814            $this->backup_dir . '/siteskite_backup_*_db.zip',
     815            $this->backup_dir . '/siteskite_backup_*_files.zip',
     816            $this->backup_dir . '/siteskite_backup_*_full.zip',
     817            $this->backup_dir . '/siteskite_backup_*.manifest',
     818            $this->backup_dir . '/siteskite_backup_*.lock',
     819            $this->backup_dir . '/siteskite_backup_*.sql',
     820            $this->backup_dir . '/siteskite_backup_*.skipped',
     821            $this->backup_dir . '/siteskite_backup_*.part',
     822        ];
     823
     824        foreach ($patterns as $pattern) {
     825            foreach (glob($pattern) ?: [] as $file) {
     826                if (!is_file($file)) {
     827                    continue;
     828                }
     829                $base = basename($file);
     830                if (!preg_match('/^(siteskite_backup_[a-zA-Z0-9]+)(?:_incremental)?_/', $base, $m)
     831                    && !preg_match('/^(siteskite_backup_[a-zA-Z0-9]+)(?:_incremental)?\./', $base, $m)
     832                ) {
     833                    continue;
     834                }
     835                $backup_id = $m[1];
     836                $has_option = false;
     837                foreach (Utils::backup_id_option_variants($backup_id) as $variant) {
     838                    if (get_option('siteskite_backup_' . $variant) !== false) {
     839                        $has_option = true;
     840                        break;
     841                    }
     842                }
     843                if ($has_option) {
     844                    continue;
     845                }
     846                if (wp_delete_file($file)) {
     847                    $this->logger->debug('Removed orphan backup package', [
     848                        'file' => $base,
     849                    ]);
     850                }
     851            }
     852        }
     853    }
     854
     855    /**
     856     * Delete per-backup options / transients / hybrid / pending-upload keys.
     857     * Also sweeps leftover SiteSkite option/transient rows that contain this backup_id
     858     * (provider status, B2 session, classic upload progress, etc.).
     859     *
     860     * @return list<string> Deleted option names
     861     */
     862    private function cleanup_backup_database_references(string $backup_id): array
     863    {
     864        $deleted_options = Utils::delete_per_backup_options($backup_id);
     865        $deleted_transients = Utils::delete_per_backup_transients($backup_id);
     866
     867        global $wpdb;
     868        $hybrid_cron_pattern = 'siteskite_hybrid_cron_%';
     869        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     870        $hybrid_cron_options = $wpdb->get_col($wpdb->prepare(
     871            "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
     872            $hybrid_cron_pattern
     873        ));
     874
     875        foreach ($hybrid_cron_options as $option_name) {
     876            foreach (Utils::backup_id_option_variants($backup_id) as $id_variant) {
     877                $option_value = get_option($option_name);
     878                if (is_array($option_value)
     879                    && isset($option_value['backup_id'])
     880                    && $option_value['backup_id'] === $id_variant
     881                ) {
     882                    if (delete_option($option_name)) {
     883                        $deleted_options[] = $option_name;
     884                    }
     885                    break;
     886                }
     887                if (strpos((string) $option_name, $id_variant) !== false) {
     888                    if (delete_option($option_name)) {
     889                        $deleted_options[] = $option_name;
     890                    }
     891                    break;
     892                }
     893            }
     894        }
     895
     896        $pending_prefix = \defined('SITESKITE_OPTION_PREFIX') ? \constant('SITESKITE_OPTION_PREFIX') : 'siteskite_';
     897        foreach (Utils::backup_id_option_variants($backup_id) as $id_variant) {
     898            $pending_upload_like = $wpdb->esc_like($pending_prefix . 'pending_upload_' . $id_variant . '_') . '%';
     899            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     900            $pending_upload_options = $wpdb->get_col($wpdb->prepare(
     901                "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
     902                $pending_upload_like
     903            ));
     904            foreach ($pending_upload_options as $pending_opt) {
     905                if (delete_option($pending_opt)) {
     906                    $deleted_options[] = $pending_opt;
     907                }
     908            }
     909        }
     910
     911        // Final sweep: any remaining SiteSkite option/transient rows that embed this backup_id
     912        // (covers new provider keys without listing every name).
     913        $swept = $this->sweep_siteskite_option_rows_for_backup_id($backup_id);
     914        foreach ($swept as $name) {
     915            $deleted_options[] = $name;
     916        }
     917
     918        if (!empty($deleted_options) || !empty($deleted_transients)) {
     919            $this->logger->info('Cleaned up database references for backup', [
     920                'backup_id' => $backup_id,
     921                'deleted_options' => $deleted_options,
     922                'deleted_transients' => $deleted_transients,
     923                'deleted_count' => count($deleted_options) + count($deleted_transients),
     924            ]);
     925        }
     926
     927        return $deleted_options;
     928    }
     929
     930    /**
     931     * Delete leftover wp_options rows for this backup_id that start with siteskite_ /
     932     * _transient_siteskite_ / _site_transient_siteskite_ (and their timeout twins).
     933     * Never touches core WP theme update transients or non-SiteSkite options.
     934     *
     935     * @return list<string>
     936     */
     937    private function sweep_siteskite_option_rows_for_backup_id(string $backup_id): array
     938    {
     939        global $wpdb;
     940        $deleted = [];
     941
     942        foreach (Utils::backup_id_option_variants($backup_id) as $id_variant) {
     943            if ($id_variant === '') {
     944                continue;
     945            }
     946            $like = '%' . $wpdb->esc_like($id_variant) . '%';
     947            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
     948            $names = $wpdb->get_col($wpdb->prepare(
     949                "SELECT option_name FROM {$wpdb->options}
     950                 WHERE option_name LIKE %s
     951                   AND (
     952                        option_name LIKE 'siteskite\\_%'
     953                     OR option_name LIKE '\\_transient\\_siteskite\\_%'
     954                     OR option_name LIKE '\\_transient\\_timeout\\_siteskite\\_%'
     955                     OR option_name LIKE '\\_site\\_transient\\_siteskite\\_%'
     956                     OR option_name LIKE '\\_site\\_transient\\_timeout\\_siteskite\\_%'
     957                   )",
     958                $like
     959            ));
     960
     961            if (!is_array($names)) {
     962                continue;
     963            }
     964
     965            foreach ($names as $option_name) {
     966                $option_name = (string) $option_name;
     967                // Never delete the external-cron job registry (site-wide, not per-backup).
     968                if ($option_name === 'siteskite_external_cron_jobs'
     969                    || $option_name === 'siteskite_cron_secret_token'
     970                    || $option_name === 'siteskite_api_key'
     971                    || $option_name === 'siteskite_callback_url'
     972                ) {
     973                    continue;
     974                }
     975
     976                if (strpos($option_name, '_transient_timeout_') === 0) {
     977                    $key = substr($option_name, strlen('_transient_timeout_'));
     978                    delete_transient($key);
     979                    $deleted[] = $option_name;
     980                    continue;
     981                }
     982                if (strpos($option_name, '_transient_') === 0) {
     983                    $key = substr($option_name, strlen('_transient_'));
     984                    delete_transient($key);
     985                    $deleted[] = $option_name;
     986                    continue;
     987                }
     988                if (strpos($option_name, '_site_transient_timeout_') === 0) {
     989                    $key = substr($option_name, strlen('_site_transient_timeout_'));
     990                    if (function_exists('delete_site_transient')) {
     991                        delete_site_transient($key);
     992                    }
     993                    $deleted[] = $option_name;
     994                    continue;
     995                }
     996                if (strpos($option_name, '_site_transient_') === 0) {
     997                    $key = substr($option_name, strlen('_site_transient_'));
     998                    if (function_exists('delete_site_transient')) {
     999                        delete_site_transient($key);
     1000                    }
     1001                    $deleted[] = $option_name;
     1002                    continue;
     1003                }
     1004
     1005                if (delete_option($option_name)) {
     1006                    $deleted[] = $option_name;
     1007                }
     1008            }
     1009        }
     1010
     1011        return array_values(array_unique($deleted));
     1012    }
     1013
     1014    /**
     1015     * Delete zip/manifest/lock/log files for one backup_id (all ID shapes).
     1016     */
     1017    private function cleanup_backup_id_files(string $backup_id): void
     1018    {
     1019        foreach (Utils::backup_id_option_variants($backup_id) as $id_variant) {
     1020            $backup_files = [
     1021                $this->backup_dir . '/' . $id_variant . '_db.zip',
     1022                $this->backup_dir . '/' . $id_variant . '_files.zip',
     1023                $this->backup_dir . '/' . $id_variant . '_full.zip',
     1024                $this->backup_dir . '/' . $id_variant . '_db.sql',
     1025                $this->backup_dir . '/' . $id_variant . '_db.lock',
     1026                $this->backup_dir . '/' . $id_variant . '_files.lock',
     1027            ];
     1028
     1029            foreach ($backup_files as $file) {
     1030                if (file_exists($file) && is_file($file)) {
     1031                    wp_delete_file($file);
     1032                    $this->logger->debug('Removed backup file', [
     1033                        'file' => basename($file),
     1034                    ]);
     1035                }
     1036            }
     1037
     1038            foreach (glob($this->backup_dir . '/' . $id_variant . '_*') ?: [] as $extra) {
     1039                if (is_file($extra)) {
     1040                    wp_delete_file($extra);
     1041                }
     1042            }
     1043        }
     1044
     1045        $log_pattern = $this->logs_dir . '/*' . $backup_id . '*.log';
     1046        foreach (glob($log_pattern) ?: [] as $log_file) {
     1047            if (is_file($log_file)) {
     1048                wp_delete_file($log_file);
     1049            }
    4561050        }
    4571051    }
  • siteskite/trunk/includes/Core/Activator.php

    r3692528 r3808895  
    77use function get_option;
    88use function add_option;
     9use function update_option;
     10use function delete_option;
    911use function flush_rewrite_rules;
    1012
    … …  
    5052            $site_url = function_exists('home_url') ? home_url() : null;
    5153            SiteSkiteSafetyCore::write_recovery_key_file($api_key, $site_url);
     54            // Restored DBs already have the Connect API key. Re-register this
     55            // host with the portal on the next admin request (sandbox staging).
     56            update_option('siteskite_pending_portal_relink', '1', false);
     57            delete_option('siteskite_pending_portal_relink_attempts');
    5258        }
    5359
  • siteskite/trunk/includes/Core/Plugin.php

    r3737950 r3808895  
    216216            $this->notification_manager = new NotificationManager($this->logger);
    217217            $this->validation_manager = new ValidationManager($this->logger);
    218             $this->cleanup_manager = new CleanupManager($this->logger);
    219218
    220219            // Initialize external cron manager
    221220            $this->external_cron_manager = new ExternalCronManager($this->logger);
     221            $this->cleanup_manager = new CleanupManager($this->logger, $this->external_cron_manager);
    222222           
    223223            // Initialize cloud storage managers
    … …  
    285285                $this->backup_manager,
    286286                $this->schedule_manager,
    287                 $this->restore_manager
     287                $this->restore_manager,
     288                $this->cleanup_manager
    288289            );
    289290
    290291            ChangeNotifyCollector::init($this->external_cron_manager, $this->logger);
    291292            ChangeNotifyHooks::register();
     293
     294            // Register daily scavenger once for updated installs (does not reschedule backups).
     295            add_action('init', [$this->cleanup_manager, 'ensure_scavenger_cron'], 30);
    292296
    293297            // Initialize REST API
    … …  
    359363        add_action('admin_menu', [$this, 'add_admin_menu']);
    360364        add_action('admin_init', [$this, 'register_settings']);
     365        // Re-link before activation redirect so staging splash can detect the sandbox.
     366        add_action('admin_init', [$this, 'maybe_relink_portal_after_restore'], 1);
    361367        add_action('admin_init', [$this, 'maybe_activation_redirect']);
    362368        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
    … …  
    598604        ]);
    599605
     606    }
     607
     608    /**
     609     * After activation on a restored site, register the current URL with the portal.
     610     *
     611     * Backups keep siteskite_api_key in the DB but the sandbox host is new.
     612     * Without this call, the plugin UI looks connected while the portal never
     613     * receives add-connect-site for the staging sandbox.
     614     */
     615    public function maybe_relink_portal_after_restore(): void {
     616        if (get_option('siteskite_pending_portal_relink') !== '1') {
     617            return;
     618        }
     619
     620        $api_key = (string) get_option('siteskite_api_key', '');
     621        if ($api_key === '') {
     622            delete_option('siteskite_pending_portal_relink');
     623            delete_option('siteskite_pending_portal_relink_attempts');
     624            return;
     625        }
     626
     627        $attempts = (int) get_option('siteskite_pending_portal_relink_attempts', 0);
     628        if ($attempts >= 3) {
     629            delete_option('siteskite_pending_portal_relink');
     630            delete_option('siteskite_pending_portal_relink_attempts');
     631            return;
     632        }
     633
     634        update_option('siteskite_pending_portal_relink_attempts', $attempts + 1, false);
     635
     636        $result = $this->auth_manager->register_site_with_portal($api_key);
     637        if ($result === true) {
     638            delete_option('siteskite_pending_portal_relink');
     639            delete_option('siteskite_pending_portal_relink_attempts');
     640        }
    600641    }
    601642
  • siteskite/trunk/includes/Core/Utils.php

    r3771884 r3808895  
    247247        $variants = [$backup_id];
    248248        $prefix = 'siteskite_backup_';
     249        $legacy_prefix = 'skte_backup_';
     250
    249251        if (str_starts_with($backup_id, $prefix)) {
    250252            $suffix = substr($backup_id, strlen($prefix));
    … …  
    252254                $variants[] = $suffix;
    253255            }
     256        } elseif (str_starts_with($backup_id, $legacy_prefix)) {
     257            // Legacy ids like skte_backup_{hex} — keep as-is; option keys are
     258            // siteskite_backup_skte_backup_{hex} / siteskite_progress_skte_backup_{hex}.
     259            $variants[] = $prefix . $backup_id;
    254260        } else {
    255261            $variants[] = $prefix . $backup_id;
     262            $variants[] = $legacy_prefix . $backup_id;
    256263        }
    257264
    … …  
    261268    /**
    262269     * Delete per-backup wp_options for all ID shapes (fixes double-prefixed keys).
     270     * Covers core backup rows plus provider status/session keys (B2, Dropbox, Drive, pCloud, AWS).
    263271     *
    264272     * @return list<string> Deleted option names
    … …  
    277285                $prefix . 'full_uploaded_' . $id,
    278286                $prefix . 'files_uploaded_' . $id,
     287                // Provider upload/status options
    279288                $prefix . 'dropbox_status_' . $id,
    280289                $prefix . 'gdrive_status_' . $id,
    … …  
    282291                $prefix . 'pcloud_status_' . $id,
    283292                $prefix . 'aws_status_' . $id,
     293                $prefix . 'b2_ul_session_' . $id,
     294                'siteskite_b2_ul_session_' . $id,
     295                // Incremental / locks
    284296                $prefix . 'incremental_progress_' . $id,
    285297                $prefix . 'all_file_paths_' . $id,
    … …  
    287299                $prefix . 'incremental_effective_chunks_per_bundle_' . $id,
    288300                $prefix . 'incremental_consecutive_successes_' . $id,
     301                $prefix . 'incremental_skip_upload_scan_only_' . $id,
    289302                'siteskite_full_backup_lock_' . $id,
    290303                'siteskite_full_backup_lock_' . $id . '_incremental',
    … …  
    303316    /**
    304317     * Delete per-backup transients for all ID shapes.
    305      */
    306     public static function delete_per_backup_transients(string $backup_id): void
    307     {
     318     * Includes classic upload progress and cloud multipart/session state.
     319     *
     320     * @return list<string> Deleted transient names (logical keys, without _transient_ prefix)
     321     */
     322    public static function delete_per_backup_transients(string $backup_id): array
     323    {
     324        $deleted = [];
    308325        if (!function_exists('delete_transient')) {
    309             return;
     326            return $deleted;
    310327        }
    311328
    … …  
    317334                'siteskite_backup_state_' . $id,
    318335                'siteskite_processed_' . $id,
     336                'siteskite_work_' . $id,
    319337                'siteskite_incremental_block_' . $id,
     338                // Classic upload progress / chunked meta
    320339                'siteskite_classic_chunked_meta_' . $id,
    321340                'siteskite_classic_ul_prog_tick_' . $id,
    322341                'siteskite_classic_ul_prog_pct_' . $id,
     342                // Provider continue-state transients
    323343                'siteskite_b2_lf_' . $id,
    324344                'siteskite_dropbox_ul_' . $id,
    325345                'siteskite_gdrive_ul_' . $id,
    326346                'siteskite_s3_mpu_' . $id,
     347                'siteskite_pcloud_ul_' . $id,
     348                'siteskite_aws_ul_' . $id,
    327349            ];
    328350
    329351            foreach ($transient_keys as $transient_key) {
    330                 delete_transient($transient_key);
    331             }
    332         }
     352                if (delete_transient($transient_key)) {
     353                    $deleted[] = $transient_key;
     354                }
     355            }
     356        }
     357
     358        return $deleted;
    333359    }
    334360
  • siteskite/trunk/includes/Cron/CronTriggerHandler.php

    r3771884 r3808895  
    77use SiteSkite\Logger\Logger;
    88use SiteSkite\Backup\BackupManager;
     9use SiteSkite\Cleanup\CleanupManager;
    910use SiteSkite\Schedule\ScheduleManager;
    1011use SiteSkite\Restore\RestoreManager;
    … …  
    2728    private ScheduleManager $schedule_manager;
    2829    private RestoreManager $restore_manager;
     30    private ?CleanupManager $cleanup_manager;
    2931
    3032    public function __construct(
    … …  
    3335        BackupManager $backup_manager,
    3436        ScheduleManager $schedule_manager,
    35         RestoreManager $restore_manager
     37        RestoreManager $restore_manager,
     38        ?CleanupManager $cleanup_manager = null
    3639    ) {
    3740        $this->logger = $logger;
    … …  
    4043        $this->schedule_manager = $schedule_manager;
    4144        $this->restore_manager = $restore_manager;
     45        $this->cleanup_manager = $cleanup_manager;
    4246    }
    4347
    … …  
    186190            }
    187191
     192            if ($action === ExternalCronManager::ACTION_BACKUP_RESUME_SAFETY_NET && is_array($args)) {
     193                $backup_id = $args[0] ?? $args['backup_id'] ?? null;
     194                if ($backup_id !== null) {
     195                    $args = [$backup_id];
     196                }
     197            }
     198
    188199            if (empty($action)) {
    189200                $this->logger->error('Missing action in cron trigger', [
    … …  
    232243            }
    233244
     245            // Safety net is a one-shot: after it is deleted, reschedule only if backup still pending.
     246            if ($action === ExternalCronManager::ACTION_BACKUP_RESUME_SAFETY_NET
     247                && is_array($result)
     248                && !empty($result['reschedule_safety_net'])
     249                && !empty($result['backup_id'])
     250            ) {
     251                $this->backup_manager->ensure_backup_resume_safety_net((string) $result['backup_id'], true);
     252            }
     253
    234254            return rest_ensure_response([
    235255                'success' => true,
    … …  
    284304            case 'siteskite_cleanup_backup_files':
    285305                return $this->handle_cleanup($args);
     306
     307            case CleanupManager::SCAVENGER_ACTION:
     308            case ExternalCronManager::ACTION_SCAVENGE_STALE_BACKUPS:
     309                return $this->handle_scavenge_stale_backups();
     310
     311            case ExternalCronManager::ACTION_BACKUP_RESUME_SAFETY_NET:
     312                return $this->handle_backup_resume_safety_net($args);
    286313
    287314            case 'siteskite_process_restore':
    … …  
    334361            'args_format' => isset($args[0]) ? 'numeric' : 'associative'
    335362        ]);
    336        
     363
     364        // Piggyback: attach resume nets to any still-open backups, then reap abandoned leftovers.
     365        // Does not require permanent heal crons for idle sites.
     366        $this->backup_manager->ensure_safety_nets_for_incomplete_backups();
     367        if ($this->cleanup_manager) {
     368            $this->cleanup_manager->ensure_scavenger_cron();
     369            $this->cleanup_manager->maybe_scavenge_stale_backups();
     370        }
     371
    337372        $this->schedule_manager->execute_scheduled_backup($type, $process_type);
    338        
     373
    339374        return [
    340375            'status' => 'executed',
    … …  
    342377            'process_type' => $process_type
    343378        ];
     379    }
     380
     381    /**
     382     * Dedicated daily scavenger cron from external cron service.
     383     *
     384     * @return array<string, mixed>
     385     */
     386    private function handle_scavenge_stale_backups(): array
     387    {
     388        // Resume first for anything still unfinished, then clean truly abandoned leftovers.
     389        $this->backup_manager->ensure_safety_nets_for_incomplete_backups();
     390
     391        if (!$this->cleanup_manager) {
     392            return [
     393                'status' => 'skipped',
     394                'reason' => 'cleanup_manager_unavailable',
     395            ];
     396        }
     397
     398        $result = $this->cleanup_manager->scavenge_stale_backups(true);
     399
     400        return [
     401            'status' => 'executed',
     402            'action' => CleanupManager::SCAVENGER_ACTION,
     403            'result' => $result,
     404        ];
     405    }
     406
     407    /**
     408     * One-shot resume safety net for a single in-progress backup.
     409     *
     410     * @param array<int|string, mixed> $args
     411     * @return array<string, mixed>
     412     */
     413    private function handle_backup_resume_safety_net(array $args): array
     414    {
     415        $backup_id = (string) ($args[0] ?? $args['backup_id'] ?? '');
     416        if ($backup_id === '') {
     417            throw new \RuntimeException('Backup ID is required');
     418        }
     419
     420        return $this->backup_manager->handle_backup_resume_safety_net($backup_id);
    344421    }
    345422
    … …  
    534611        do_action('siteskite_cleanup_backup_files', $backup_id);
    535612
     613        // After per-backup cleanup, run throttled scavenger as a second guard.
     614        if ($this->cleanup_manager) {
     615            $this->cleanup_manager->maybe_scavenge_stale_backups();
     616        }
     617
    536618        return [
    537619            'status' => 'executed',
  • siteskite/trunk/includes/Cron/ExternalCronManager.php

    r3771884 r3808895  
    3838    public const ACTION_B2_CONTINUE_LARGE_UPLOAD = 'siteskite_b2_continue_large_upload';
    3939
     40    /** Daily janitor for stranded backup options/files (not per-backup). */
     41    public const ACTION_SCAVENGE_STALE_BACKUPS = 'siteskite_scavenge_stale_backups';
     42
     43    /**
     44     * One-shot resume check while a backup is still pending.
     45     * Created on backup start, rescheduled only if still incomplete, deleted on finish.
     46     */
     47    public const ACTION_BACKUP_RESUME_SAFETY_NET = 'siteskite_backup_resume_safety_net';
     48
    4049    /** @var list<string> */
    4150    public const PROTECTED_ACTIONS = [
    4251        self::ACTION_SCHEDULED_BACKUP,
     52        self::ACTION_SCAVENGE_STALE_BACKUPS,
    4353    ];
    4454
    … …  
    5767        'process_full_backup_final_zip_cron',
    5868        'siteskite_cleanup_backup_files',
     69        self::ACTION_BACKUP_RESUME_SAFETY_NET,
    5970    ];
    6071
    … …  
    816827
    817828    /**
    818      * Convert WordPress frequency to cron-job.org schedule
     829     * Resolve an IANA timezone from schedule options. Falls back to UTC when missing/invalid.
     830     */
     831    private function resolve_timezone(array $options): string
     832    {
     833        $tz = isset($options['timezone']) ? trim((string) $options['timezone']) : '';
     834        if ($tz === '') {
     835            return 'UTC';
     836        }
     837
     838        try {
     839            new \DateTimeZone($tz);
     840            return $tz;
     841        } catch (\Exception $e) {
     842            $this->logger->warning('Invalid schedule timezone, falling back to UTC', [
     843                'timezone' => $tz,
     844                'error' => $e->getMessage(),
     845            ]);
     846            return 'UTC';
     847        }
     848    }
     849
     850    /**
     851     * Convert WordPress frequency to cron-job.org schedule.
     852     * Wall-clock time (hours/minutes) is interpreted in options['timezone'] (from the portal).
    819853     */
    820854    private function convert_frequency_to_schedule(string $frequency, array $options = []): array
    821855    {
    822856        $schedule = [
    823             'timezone' => 'UTC',
     857            'timezone' => $this->resolve_timezone($options),
    824858            'hours' => [-1],
    825859            'mdays' => [-1],
  • siteskite/trunk/includes/Cron/RestAPI.php

    r3771884 r3808895  
    14241424                'day' => $request->get_param('day'),
    14251425                'date' => (int) $request->get_param('date'),
     1426                'timezone' => $request->get_param('timezone') ?: 'UTC',
    14261427                'callback_url' => $request->get_param('callback_url'),
    14271428            ];
  • siteskite/trunk/includes/Schedule/ScheduleManager.php

    r3771884 r3808895  
    646646                'time' => $schedule['time'],
    647647                'day' => $schedule['day'],
    648                 'date' => $schedule['date']
     648                'date' => $schedule['date'],
     649                'timezone' => $schedule['timezone'] ?? 'UTC',
    649650            ]
    650651        );
    … …  
    735736
    736737    /**
    737      * Calculate next run time
     738     * Calculate next run time in the schedule's timezone (portal choice),
     739     * falling back to the WordPress site timezone, then UTC.
    738740     */
    739741    private function calculate_next_run(string $frequency, array $options = []): int
    … …  
    741743        $now = time();
    742744        $timezone = wp_timezone();
     745        $tzName = isset($options['timezone']) ? trim((string) $options['timezone']) : '';
     746        if ($tzName !== '') {
     747            try {
     748                $timezone = new \DateTimeZone($tzName);
     749            } catch (\Exception $e) {
     750                // Keep wp_timezone() when the schedule timezone is invalid.
     751            }
     752        }
    743753        $datetime = new \DateTime('now', $timezone);
    744754
    … …  
    868878            $schedule_data['callback_url'] = $schedule_callback;
    869879
    870             // Create new schedule
     880            // Create new schedule — timezone comes from the portal (IANA), UTC only if omitted.
    871881            $backup_id = 'siteskite_backup_' . uniqid();
     882            $timezone = isset($schedule_data['timezone']) && trim((string) $schedule_data['timezone']) !== ''
     883                ? trim((string) $schedule_data['timezone'])
     884                : 'UTC';
     885            $schedule_options = [
     886                'time' => $schedule_data['time'] ?? '00:00',
     887                'day' => $schedule_data['day'] ?? '',
     888                'date' => $schedule_data['date'] ?? 1,
     889                'timezone' => $timezone,
     890            ];
    872891            $schedule = [
    873892                'id' => 'siteskite_schedule_' . uniqid(),
    … …  
    875894                'type' => $schedule_data['type'],
    876895                'frequency' => $schedule_data['frequency'],
    877                 'time' => $schedule_data['time'] ?? '00:00',
    878                 'day' => $schedule_data['day'] ?? '',
    879                 'date' => $schedule_data['date'] ?? 1,
     896                'time' => $schedule_options['time'],
     897                'day' => $schedule_options['day'],
     898                'date' => $schedule_options['date'],
     899                'timezone' => $timezone,
    880900                'enabled' => true,
    881901                'callback_url' => $schedule_callback,
    … …  
    883903                'next_run' => $this->calculate_next_run(
    884904                    $schedule_data['frequency'],
    885                     [
    886                         'time' => $schedule_data['time'] ?? '00:00',
    887                         'day' => $schedule_data['day'] ?? '',
    888                         'date' => $schedule_data['date'] ?? 1
    889                     ]
     905                    $schedule_options
    890906                )
    891907            ];
    … …  
    905921                    [$schedule_data['type'], 'automatic'],
    906922                    $schedule_data['frequency'],
    907                     [
    908                         'time' => $schedule_data['time'] ?? '00:00',
    909                         'day' => $schedule_data['day'] ?? '',
    910                         'date' => $schedule_data['date'] ?? 1
    911                     ],
     923                    $schedule_options,
    912924                    "SiteSkite: Scheduled Backup ({$schedule_data['type']})"
    913925                );
    … …  
    922934                        'job_id' => $job_id,
    923935                        'type' => $schedule_data['type'],
    924                         'frequency' => $schedule_data['frequency']
     936                        'frequency' => $schedule_data['frequency'],
     937                        'timezone' => $timezone,
     938                        'time' => $schedule_options['time'],
    925939                    ]);
    926940                } else {
  • siteskite/trunk/readme.txt

    r3797113 r3808895  
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 2.2.13
     7Stable tag: 2.2.14
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    317317== Changelog ==
    318318
     319= 2.2.14 (16 November 2026) =
     320* Improved: Backup reliability.
     321
    319322= 2.2.13 (12 November 2026) =
    320323* New: AI can inspect plugin settings read-only — LiteSpeed Cache, Elementor, Elementor Pro, Rank Math SEO, WooCommerce, Tutor LMS, and Slider Revolution — without changing anything. Secrets such as API keys and licenses are hidden. Works while MCP Read-only mode is on, and does not need Advanced Power Tools.
    … …  
    544547== Upgrade Notice ==
    545548
     549= 2.2.14 (16 November 2026) =
     550Improves backup reliability.
     551
    546552= 2.2.13 (12 November 2026) =
    547553AI can inspect LiteSpeed, Elementor, Rank Math, WooCommerce, Tutor LMS, and Slider Revolution settings read-only (secrets hidden). Advanced Power Tools stay off by default until you enable them.
  • siteskite/trunk/siteskite-link.php

    r3797113 r3808895  
    44 * Plugin URI: https://siteskite.com
    55 * Description: Connect your WordPress site to SiteSkite for updates, backups, monitoring, and complete control — all in one place.
    6  * Version: 2.2.13
     6 * Version: 2.2.14
    77 * Requires at least: 5.3
    88 * Requires PHP: 7.4
    … …  
    2929
    3030// Plugin version
    31 define('SITESKITE_VERSION', '2.2.13');
     31define('SITESKITE_VERSION', '2.2.14');
    3232
    3333// Plugin file, path, and URL
Note: See TracChangeset for help on using the changeset viewer.