$item ) { if ( ! is_array( $item ) || ! isset( $item[2] ) || 'uxpack' !== $item[2] ) { continue; } $menu[ $index ][0] = $title; break; } } /** * Max backups shown in the dashboard widget. */ const DASHBOARD_RECENT_BACKUPS = 5; /** * Max error entries shown in the dashboard widget. */ const DASHBOARD_RECENT_ERRORS = 5; /** * Register dashboard widget for quick backup overview and trigger. */ public function register_dashboard_widget() { if ( ! UXPack_Capabilities::current_user_can( 'view_backups' ) ) { return; } wp_add_dashboard_widget( 'uxpack_dashboard_backup', __( 'UXPack', 'uxpack-basic' ), array( $this, 'render_dashboard_widget' ) ); } /** * Render dashboard widget content. */ public function render_dashboard_widget() { if ( ! UXPack_Capabilities::current_user_can( 'view_backups' ) ) { return; } $backups_url = admin_url( 'admin.php?page=uxpack' ); $log_url = admin_url( 'admin.php?page=uxpack-log' ); $backups = UXPack_Backup::get_backups(); $recent = array_slice( $backups, 0, UXPack_License::is_basic() ? UXPack_License::BASIC_DASHBOARD_BACKUPS : self::DASHBOARD_RECENT_BACKUPS ); $recent_errors = self::get_recent_log_errors( self::DASHBOARD_RECENT_ERRORS ); $log_enabled = (int) get_option( 'uxpack_enable_log', 1 ) === 1; $can_run = UXPack_Capabilities::current_user_can( 'run_backups' ); $health_warnings = class_exists( 'UXPack_Health', false ) ? UXPack_Health::get_warnings() : array(); ?>

0 ) { $errors = array_slice( $errors, 0, $limit ); } return $errors; } /** * Enqueue admin scripts and styles. * * @param string $hook */ public function enqueue_scripts( $hook ) { $is_uxpack_page = strpos( $hook, 'uxpack' ) !== false; $is_dashboard = 'index.php' === $hook; if ( ! $is_uxpack_page && ! $is_dashboard ) { return; } // Dashboard widget needs styles for the tier badge; UXPack pages need full admin assets. if ( $is_dashboard ) { if ( ! UXPack_Capabilities::current_user_can( 'view_backups' ) && ! UXPack_Capabilities::current_user_can( 'access' ) ) { return; } } elseif ( ! UXPack_Capabilities::current_user_can( 'access' ) ) { return; } wp_enqueue_style( 'dashicons' ); $admin_css = UXPACK_PLUGIN_DIR . 'assets/admin.css'; $admin_css_ver = UXPACK_VERSION; if ( is_readable( $admin_css ) ) { $admin_css_mtime = filemtime( $admin_css ); if ( false !== $admin_css_mtime ) { $admin_css_ver = UXPACK_VERSION . '.' . (string) $admin_css_mtime; } } wp_enqueue_style( 'uxpack-admin', UXPACK_PLUGIN_URL . 'assets/admin.css', array( 'dashicons' ), $admin_css_ver ); if ( class_exists( 'UXPack_Pro_Mocks', false ) ) { UXPack_Pro_Mocks::enqueue( $hook ); } // Dashboard only needs the badge styles; skip the heavy admin.js there. if ( $is_dashboard && ! $is_uxpack_page ) { return; } $admin_js = UXPACK_PLUGIN_DIR . 'assets/admin.js'; $admin_js_ver = UXPACK_VERSION; if ( is_readable( $admin_js ) ) { $admin_js_mtime = filemtime( $admin_js ); if ( false !== $admin_js_mtime ) { $admin_js_ver = UXPACK_VERSION . '.' . (string) $admin_js_mtime; } } wp_enqueue_script( 'uxpack-admin', UXPACK_PLUGIN_URL . 'assets/admin.js', array( 'jquery' ), $admin_js_ver, true ); $backup_timeout_ms = (int) apply_filters( 'uxpack_backup_ajax_timeout_ms', 3600000 ); // 60 minutes default if ( $backup_timeout_ms < 60000 ) { $backup_timeout_ms = 60000; // minimum 1 minute } $has_encryption = class_exists( 'UXPack_Encryption', false ); wp_localize_script( 'uxpack-admin', 'uxpackData', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'uxpack_backup' ), 'backupTimeout' => $backup_timeout_ms, 'pollInterval' => 3000, 'encryptEnabled' => $has_encryption && UXPack_Encryption::is_encryption_enabled(), 'encryptionMode' => $has_encryption ? UXPack_Encryption::get_encryption_mode() : 'off', 'sitePasswordReady' => $has_encryption && 'ok' === UXPack_Encryption::get_site_password_indicator_state(), 'minPasswordLength' => $has_encryption ? UXPack_Encryption::MIN_PASSWORD_LENGTH : 12, 'currentTablePrefix' => isset( $GLOBALS['wpdb']->prefix ) ? (string) $GLOBALS['wpdb']->prefix : '', 'canRunBackups' => UXPack_Capabilities::current_user_can( 'run_backups' ), 'isMultisite' => is_multisite(), 'licenseTier' => UXPack_License::get_tier(), 'isPro' => UXPack_License::is_pro(), 'directoryEdition' => UXPack_License::is_directory_edition(), 'licenseFeatures' => UXPack_License::get_feature_flags_for_js(), 'settingsProOnlyTabs' => self::get_settings_pro_only_tabs(), 'settingsUrl' => UXPack_License::get_settings_url(), 'restorePage' => ( 'uxpack_page_uxpack-restore' === $hook ), 'backupsPage' => ( 'toplevel_page_uxpack' === $hook ), 'logPage' => ( 'uxpack_page_uxpack-log' === $hook ), 'i18n' => array( 'confirmDelete' => __( 'Are you sure you want to delete this backup?', 'uxpack-basic' ), 'confirmBulkDelete' => __( 'Delete the selected backups? This cannot be undone.', 'uxpack-basic' ), 'cancel' => __( 'Cancel', 'uxpack-basic' ), 'ok' => __( 'OK', 'uxpack-basic' ), 'delete' => __( 'Delete', 'uxpack-basic' ), 'deleting' => __( 'Deleting...', 'uxpack-basic' ), 'deletingSelected' => __( 'Deleting selected...', 'uxpack-basic' ), 'deleteSelected' => __( 'Delete selected', 'uxpack-basic' ), 'downloading' => __( 'Downloading…', 'uxpack-basic' ), 'chainPackageDownload' => __( 'Download chain package', 'uxpack-basic' ), 'chainPackagePreparing' => __( 'Preparing chain package…', 'uxpack-basic' ), 'downloadComplete' => __( 'Download complete.', 'uxpack-basic' ), 'downloadFailed' => __( 'Download failed.', 'uxpack-basic' ), 'emptyState' => __( 'No backups yet. Create your first backup above.', 'uxpack-basic' ), 'backupRunning' => __( 'Backup in progress...', 'uxpack-basic' ), 'backupPreparing' => __( 'Preparing backup…', 'uxpack-basic' ), 'encryptionRunning' => __( 'Encryption in progress...', 'uxpack-basic' ), 'backupKeepPageOpen' => __( 'Keep this page open until the backup finishes. Leaving pauses the backup; return within about 15 minutes to continue.', 'uxpack-basic' ), 'backupCancelling' => __( 'Cancelling backup...', 'uxpack-basic' ), 'backupCancelled' => __( 'Backup cancelled.', 'uxpack-basic' ), 'cancelBackup' => __( 'Cancel backup', 'uxpack-basic' ), 'confirmCancelBackup' => __( 'Cancel this backup? Partial archive files will be removed. The backup may continue briefly while the current step finishes.', 'uxpack-basic' ), 'forceClearBackup' => __( 'Force stop', 'uxpack-basic' ), 'confirmForceClearBackup' => __( 'Clear the stuck backup status and remove partial archive files? Use this when the server was restarted or the backup process is no longer running.', 'uxpack-basic' ), 'success' => __( 'Backup completed successfully.', 'uxpack-basic' ), 'error' => __( 'An error occurred.', 'uxpack-basic' ), 'zipFinalizeFailed' => UXPack_Zip::get_zip_finalize_error_message( '' ), 'requestInterrupted' => __( 'The request was interrupted (e.g. timeout). The backup status could not be confirmed.', 'uxpack-basic' ), 'refreshToCheck' => __( 'Please refresh the page and check the backup list to confirm the result.', 'uxpack-basic' ), 'checkLogHint' => __( 'Open UXPack → Activity Log for details.', 'uxpack-basic' ), 'selectOne' => __( 'Please select at least one backup.', 'uxpack-basic' ), 'confirmClearLog' => __( 'Delete the entire backup log? This cannot be undone.', 'uxpack-basic' ), 'clearLog' => __( 'Clear log', 'uxpack-basic' ), 'logClearing' => __( 'Clearing log…', 'uxpack-basic' ), 'logCleared' => __( 'Backup log cleared.', 'uxpack-basic' ), 'logClearFailed' => __( 'Could not clear the backup log.', 'uxpack-basic' ), 'logEmpty' => __( 'No backup log entries yet.', 'uxpack-basic' ), 'logFilteredEmpty' => __( 'No entries match the current filters.', 'uxpack-basic' ), 'logFiltering' => __( 'Filtering log…', 'uxpack-basic' ), /* translators: 1: number of visible log entries, 2: total log entries */ 'logFilterSummary' => __( 'Showing %1$s of %2$s entries.', 'uxpack-basic' ), 'logFilterBackupAll' => __( 'All backups', 'uxpack-basic' ), 'confirmResetSettings' => __( 'Reset all settings on this page to their default values? This cannot be undone.', 'uxpack-basic' ), 'confirmResetStorage' => __( 'Delete the entire backup storage directory and all backups inside it? This cannot be undone.', 'uxpack-basic' ), 'confirmResetBoth' => __( 'Reset all settings to their default values and delete the entire backup storage directory? This cannot be undone.', 'uxpack-basic' ), 'resetSelectOption' => __( 'Please select at least one reset option.', 'uxpack-basic' ), 'resetSettings' => __( 'Reset', 'uxpack-basic' ), 'resetRunning' => __( 'Resetting…', 'uxpack-basic' ), 'resetFailed' => __( 'Reset could not be completed.', 'uxpack-basic' ), 'confirmImportSettings' => __( 'Import settings from this file? Current settings on this page will be overwritten for every option included in the file.', 'uxpack-basic' ), 'confirmExportIncludeLicense' => __( 'Include the license email and key in this download? Anyone with the file can use those credentials. Continue only if you will store the file securely.', 'uxpack-basic' ), 'downloadSettings' => __( 'Download settings', 'uxpack-basic' ), 'importSettings' => __( 'Import settings', 'uxpack-basic' ), 'settingsImportNoFile' => __( 'Please choose a settings file.', 'uxpack-basic' ), 'settingsImportInvalidFile' => __( 'Please choose a valid UXPack settings JSON file.', 'uxpack-basic' ), /* translators: %s: selected settings filename */ 'settingsImportFileSelected' => __( 'Selected file: %s', 'uxpack-basic' ), 'scheduleTestRun' => __( 'Run diagnostics', 'uxpack-basic' ), 'scheduleTestRunning' => __( 'Running diagnostics…', 'uxpack-basic' ), /* translators: %s: name of the diagnostic check currently running */ 'scheduleTestProgress' => __( 'Checking: %s', 'uxpack-basic' ), 'scheduleTestFailed' => __( 'Diagnostics could not be completed.', 'uxpack-basic' ), /* translators: 1: number of passed checks, 2: number of warnings, 3: number of failed checks */ 'scheduleTestSummary' => __( 'Results: %1$d passed, %2$d warnings, %3$d failed.', 'uxpack-basic' ), 'scheduleTestPass' => __( 'Pass', 'uxpack-basic' ), 'scheduleTestWarning' => __( 'Warning', 'uxpack-basic' ), 'scheduleTestFail' => __( 'Failed', 'uxpack-basic' ), 'scheduleTestStepPhpVersion' => __( 'PHP version', 'uxpack-basic' ), 'scheduleTestStepMemory' => __( 'PHP memory limit', 'uxpack-basic' ), 'scheduleTestStepZipArchive' => __( 'ZipArchive extension', 'uxpack-basic' ), 'scheduleTestStepMysqli' => __( 'mysqli extension', 'uxpack-basic' ), 'scheduleTestStepZipEncrypt' => __( 'ZIP encryption', 'uxpack-basic' ), 'scheduleTestStepAes256' => __( 'AES-256 ZIP encryption', 'uxpack-basic' ), 'scheduleTestStepOpenSsl' => __( 'OpenSSL (encrypted sidecar)', 'uxpack-basic' ), 'scheduleTestStepWpRoot' => __( 'WordPress root readable', 'uxpack-basic' ), 'scheduleTestStepStoragePath' => __( 'Backup storage path', 'uxpack-basic' ), 'scheduleTestStepStorageWrite'=> __( 'Backup storage writable', 'uxpack-basic' ), 'scheduleTestStepDiskFree' => __( 'Free disk space', 'uxpack-basic' ), 'scheduleTestStepBackupIdle' => __( 'No backup in progress', 'uxpack-basic' ), 'scheduleTestStepRestoreIdle' => __( 'No restore in progress', 'uxpack-basic' ), 'scheduleTestStepEnabled' => __( 'Schedule enabled', 'uxpack-basic' ), 'scheduleTestStepTime' => __( 'Site time', 'uxpack-basic' ), 'scheduleTestStepNextRun' => __( 'Next run stored', 'uxpack-basic' ), 'scheduleTestStepDue' => __( 'Backup due now', 'uxpack-basic' ), 'scheduleTestStepBackupRun' => __( 'Backup in progress', 'uxpack-basic' ), 'scheduleTestStepWpCron' => __( 'DISABLE_WP_CRON', 'uxpack-basic' ), 'excludeTreeExpand' => __( 'Expand folder', 'uxpack-basic' ), 'excludeTreeCollapse' => __( 'Collapse folder', 'uxpack-basic' ), 'excludeTreeLoading' => __( 'Loading folders…', 'uxpack-basic' ), 'excludeTreeAlwaysExcluded' => __( 'Always excluded', 'uxpack-basic' ), 'excludeTreePartial' => __( 'Contains exclusions', 'uxpack-basic' ), 'excludeTreeSystemWarning' => __( 'You excluded WordPress system folders (wp-admin, wp-content, or wp-includes). The installer may then not restore a fully working website.', 'uxpack-basic' ), 'excludeTreeEmpty' => __( 'No subfolders.', 'uxpack-basic' ), 'excludeTreeLoadError' => __( 'Could not load folders.', 'uxpack-basic' ), 'scheduleTestStepCronSingle' => __( 'WordPress cron: scheduled backup event', 'uxpack-basic' ), 'scheduleTestStepCronTick' => __( 'WordPress cron: 15-minute tick', 'uxpack-basic' ), 'scheduleTestStepSpawn' => __( 'spawn_cron() available', 'uxpack-basic' ), 'scheduleTestStepTickRun' => __( 'Schedule tick executed', 'uxpack-basic' ), 'scheduleListEmpty' => __( 'No schedules yet. Add one to run backups automatically.', 'uxpack-basic' ), 'scheduleEnabled' => __( 'Enabled', 'uxpack-basic' ), 'scheduleDisabled' => __( 'Disabled', 'uxpack-basic' ), 'scheduleNotScheduled' => __( 'Not scheduled', 'uxpack-basic' ), 'scheduleSuccess' => __( 'Success', 'uxpack-basic' ), 'scheduleSkipped' => __( 'Skipped', 'uxpack-basic' ), 'scheduleError' => __( 'Error', 'uxpack-basic' ), 'scheduleNever' => __( 'Never', 'uxpack-basic' ), 'scheduleEdit' => __( 'Edit', 'uxpack-basic' ), 'scheduleDelete' => __( 'Delete', 'uxpack-basic' ), 'scheduleDeleted' => __( 'Schedule deleted.', 'uxpack-basic' ), 'scheduleAddTitle' => __( 'Add schedule', 'uxpack-basic' ), 'scheduleEditTitle' => __( 'Edit schedule', 'uxpack-basic' ), 'scheduleNewTab' => __( 'New schedule', 'uxpack-basic' ), 'scheduleOverviewTab' => __( 'Overview', 'uxpack-basic' ), /* translators: %s: schedule name */ 'confirmDeleteSchedule' => __( 'Delete schedule “%s”?', 'uxpack-basic' ), 'scheduleColName' => __( 'Name', 'uxpack-basic' ), 'scheduleColStatus' => __( 'Status', 'uxpack-basic' ), 'scheduleColSchedule' => __( 'Schedule', 'uxpack-basic' ), 'scheduleColType' => __( 'Backup type', 'uxpack-basic' ), 'scheduleColNext' => __( 'Next run', 'uxpack-basic' ), 'scheduleColLast' => __( 'Last run', 'uxpack-basic' ), 'scheduleColBackupStatus' => __( 'Backup status', 'uxpack-basic' ), 'scheduleColActions' => __( 'Actions', 'uxpack-basic' ), /* translators: 1: number of used schedule slots, 2: maximum schedule slots */ 'scheduleSlots' => __( '%1$d of %2$d schedule slots', 'uxpack-basic' ), 'backupDetails' => __( 'Backup details', 'uxpack-basic' ), 'backupDetailsClose' => __( 'Close', 'uxpack-basic' ), 'backupLabel' => __( 'Label', 'uxpack-basic' ), 'backupLabelEdit' => __( 'Edit label', 'uxpack-basic' ), 'backupLabelPrompt' => __( 'Enter a label for this backup (optional).', 'uxpack-basic' ), 'backupLabelSave' => __( 'Save label', 'uxpack-basic' ), 'backupLabelSaved' => __( 'Label saved.', 'uxpack-basic' ), 'backupLabelSaveFailed' => __( 'Could not save label.', 'uxpack-basic' ), 'backupLabelPlaceholder' => __( 'Optional label', 'uxpack-basic' ), 'viewDetails' => __( 'View backup details', 'uxpack-basic' ), 'sendTestEmail' => __( 'Send test email', 'uxpack-basic' ), 'sendingTestEmail' => __( 'Sending test email…', 'uxpack-basic' ), 'testEmailSent' => __( 'Test email sent.', 'uxpack-basic' ), 'testEmailFailed' => __( 'Test email could not be sent.', 'uxpack-basic' ), 'remoteConnecting' => __( 'Connecting…', 'uxpack-basic' ), 'remoteConnect' => __( 'Connect', 'uxpack-basic' ), 'remoteConnectFailed' => __( 'Could not start connection.', 'uxpack-basic' ), 'remoteDisconnect' => __( 'Disconnect', 'uxpack-basic' ), 'remoteDisconnectConfirm' => __( 'Disconnect this remote storage account?', 'uxpack-basic' ), 'remoteDisconnecting' => __( 'Disconnecting…', 'uxpack-basic' ), 'remoteDisconnected' => __( 'Disconnected.', 'uxpack-basic' ), 'remoteEnabled' => __( 'Enabled', 'uxpack-basic' ), 'remoteDisabled' => __( 'Disabled', 'uxpack-basic' ), 'remoteConnected' => __( 'Connected', 'uxpack-basic' ), 'remoteNotConnected' => __( 'Not connected', 'uxpack-basic' ), 'remoteTestUpload' => __( 'Upload test backup', 'uxpack-basic' ), 'remoteUploading' => __( 'Uploading…', 'uxpack-basic' ), /* translators: %s: upload percent number (0–100), without a percent sign */ 'remoteUploadingPct' => __( 'Uploading to remote storage… %s%', 'uxpack-basic' ), 'remoteUploadOk' => __( 'Upload completed.', 'uxpack-basic' ), 'remoteUploadFailed' => __( 'Upload failed.', 'uxpack-basic' ), 'remoteUploadTimeout' => __( 'Upload timed out. Try a smaller backup or raise the PHP max_execution_time.', 'uxpack-basic' ), 'destinationsRequired' => __( 'Select at least one destination.', 'uxpack-basic' ), 'destinationsLocal' => __( 'Local storage', 'uxpack-basic' ), 'destinationsChoose' => __( 'Choose destinations', 'uxpack-basic' ), 'manageRemoteStorage' => __( 'Manage remote storage', 'uxpack-basic' ), 'copied' => __( 'Copied', 'uxpack-basic' ), 'copyRedirectUri' => __( 'Copy redirect URI:', 'uxpack-basic' ), 'restore' => __( 'Restore', 'uxpack-basic' ), 'restoreRunning' => __( 'Restore in progress…', 'uxpack-basic' ), 'restoreSuccess' => __( 'Backup restored successfully.', 'uxpack-basic' ), 'restoreFailed' => __( 'Restore failed.', 'uxpack-basic' ), 'restoreModeLabel' => __( 'Restore scope', 'uxpack-basic' ), 'restoreModeFull' => __( 'Files and database', 'uxpack-basic' ), 'restoreModeDb' => __( 'Database only', 'uxpack-basic' ), 'restoreModeFiles' => __( 'Files only', 'uxpack-basic' ), 'restoreFilesSuccess' => __( 'Site files restored successfully.', 'uxpack-basic' ), 'restorePhaseValidating' => __( 'Validating backup…', 'uxpack-basic' ), 'restorePhaseExtracting' => __( 'Extracting files…', 'uxpack-basic' ), 'restorePhaseImporting' => __( 'Importing database…', 'uxpack-basic' ), 'restorePhaseFinalizing' => __( 'Finalizing restore…', 'uxpack-basic' ), 'restoreBackupBefore' => __( 'Create a backup before restore', 'uxpack-basic' ), 'restoreBackupBeforeHint' => __( 'Recommended. Saves the current site before overwriting it.', 'uxpack-basic' ), 'restoreTablePrefix' => __( 'Table prefix', 'uxpack-basic' ), 'restoreTablePrefixHint' => __( 'Optional. Leave blank to use the current prefix from wp-config.php.', 'uxpack-basic' ), 'restoreTablePrefixInvalid' => __( 'The table prefix may only contain letters, numbers, and underscores.', 'uxpack-basic' ), 'restoreBackupBeforeDenied' => __( 'You do not have permission to create backups.', 'uxpack-basic' ), 'restorePreBackupRunning' => __( 'Creating pre-restore backup…', 'uxpack-basic' ), 'restoreUploadTitle' => __( 'Upload backup', 'uxpack-basic' ), 'restoreUploadHint' => __( 'Drag and drop a UXPack ZIP archive here, or choose a file.', 'uxpack-basic' ), 'restoreUploadChoose' => __( 'Choose file', 'uxpack-basic' ), 'restoreUploadRunning' => __( 'Uploading backup…', 'uxpack-basic' ), 'restoreUploadSuccess' => __( 'Backup uploaded.', 'uxpack-basic' ), 'restoreUploadFailed' => __( 'Upload failed.', 'uxpack-basic' ), 'restoreSelectBackup' => __( 'Backup archive', 'uxpack-basic' ), 'restoreSelectBackupHint' => __( 'Choose a backup from storage or upload an external UXPack ZIP.', 'uxpack-basic' ), 'restoreMultisiteWarning' => __( 'Multisite compatibility notice', 'uxpack-basic' ), 'restoreRun' => __( 'Run restore', 'uxpack-basic' ), 'restoreNoBackupSelected' => __( 'Please select or upload a backup first.', 'uxpack-basic' ), 'backupPasswordRequired' => __( 'Please enter a backup password.', 'uxpack-basic' ), 'backupPasswordMismatch' => __( 'Backup passwords do not match.', 'uxpack-basic' ), /* translators: %d: minimum password length */ 'backupPasswordTooShort' => __( 'The backup password must be at least %d characters long.', 'uxpack-basic' ), 'backupPasswordOverrideHint'=> __( 'Optional: enter a one-time password to override the site password for this backup.', 'uxpack-basic' ), 'restorePasswordRequired' => __( 'Please enter the backup password.', 'uxpack-basic' ), 'verify' => __( 'Verify', 'uxpack-basic' ), 'verifyRunning' => __( 'Verifying backup…', 'uxpack-basic' ), 'verifyModalTitle' => __( 'Verify backup', 'uxpack-basic' ), 'verifyModalMessage' => __( 'Checks whether the archive is readable and contains a valid manifest and database dump.', 'uxpack-basic' ), 'verifyModalConfirm' => __( 'Run verification', 'uxpack-basic' ), 'verifyFailed' => __( 'Verification could not be completed.', 'uxpack-basic' ), 'verifyPass' => __( 'Pass', 'uxpack-basic' ), 'verifyWarning' => __( 'Warning', 'uxpack-basic' ), 'verifyFail' => __( 'Failed', 'uxpack-basic' ), 'verifyClose' => __( 'Close', 'uxpack-basic' ), 'showPassword' => __( 'Show password', 'uxpack-basic' ), 'hidePassword' => __( 'Hide password', 'uxpack-basic' ), 'settingsSaving' => __( 'Saving settings…', 'uxpack-basic' ), 'settingsSaved' => __( 'Settings saved.', 'uxpack-basic' ), 'settingsSaveFailed' => __( 'Settings could not be saved.', 'uxpack-basic' ), 'licenseServicePending' => __( 'Checking license service…', 'uxpack-basic' ), 'updateServerPending' => __( 'Checking update server…', 'uxpack-basic' ), 'backupLocked' => __( 'Locked', 'uxpack-basic' ), 'backupUnlocked' => __( 'Unlocked', 'uxpack-basic' ), 'backupLockToggle' => __( 'Lock backup', 'uxpack-basic' ), 'backupUnlockToggle' => __( 'Unlock backup', 'uxpack-basic' ), 'backupLockedDelete' => __( 'This backup is locked and cannot be deleted.', 'uxpack-basic' ), 'backupLockSaved' => __( 'Backup lock updated.', 'uxpack-basic' ), 'backupLockSaveFailed' => __( 'Could not update backup lock.', 'uxpack-basic' ), 'proRequired' => UXPack_License::get_upgrade_message(), ), ) ); $admin_pro_js = UXPACK_PLUGIN_DIR . 'assets/admin-pro.js'; if ( class_exists( 'UXPack_Admin_Pro', false ) && is_readable( $admin_pro_js ) ) { $admin_pro_js_ver = UXPACK_VERSION; $admin_pro_js_mtime = filemtime( $admin_pro_js ); if ( false !== $admin_pro_js_mtime ) { $admin_pro_js_ver = UXPACK_VERSION . '.' . (string) $admin_pro_js_mtime; } wp_enqueue_script( 'uxpack-admin-pro', UXPACK_PLUGIN_URL . 'assets/admin-pro.js', array( 'jquery', 'uxpack-admin' ), $admin_pro_js_ver, true ); } } /** * Render a notice when the current install is not licensed for Pro. * * Also used by directory Basic mock templates (UXPack_Pro_Mocks). * * @return void */ public static function render_license_upgrade_notice() { if ( UXPack_License::is_pro() ) { return; } ?>

UXPack Pro. Upgrade to restore in the admin, encrypt backups, use retention and remote storage, and more. %1$sSee all Pro features%2$s.', 'uxpack-basic' ), '', '' ) ); } else { echo wp_kses_post( sprintf( /* translators: 1: opening settings anchor, 2: closing settings anchor, 3: opening buy-license anchor, 4: closing buy-license anchor */ __( 'This page or parts of it require UXPack Pro. %1$sEnter your license key%2$s under Settings → General, or %3$sbuy a license at getuxpack.com%4$s.', 'uxpack-basic' ), '', '', '', '' ) ); } ?>

', esc_attr( trim( $class . ( $locked ? ' uxpack-pro-gated-fieldset' : '' ) ) ), $locked ? ' disabled' : '' ); } /** * Close a Pro-gated fieldset opened with open_pro_gated_fieldset(). */ public function close_pro_gated_fieldset() { echo ''; } /** * Settings tabs where every control is Pro-only (Save disabled / hidden on Basic). * * Directory Basic uses mock panels and never locks via is_ui_locked(); those tabs * are still marked locked here so Save stays unavailable. * * @return array Tab id => whether save is locked on the current tier. */ private static function get_settings_pro_only_tabs() { // Tabs whose module markup is Pro-only (omitted or license-gated as a whole). // Shipped Basic features (email, exclude, verify, …) are never listed here. $pro_tabs = array( 'updates' => UXPack_License::FEATURE_BACKUP_BEFORE_UPDATE, 'backup-optimize' => UXPack_License::FEATURE_PRE_BACKUP_OPTIMIZE, 'backup-encryption' => UXPack_License::FEATURE_ENCRYPTION, ); $tabs = array( 'general' => false, 'activity-log' => false, 'email' => false, 'backup-contents' => false, 'restore-verification' => false, 'storage' => false, 'export' => false, 'import' => false, ); foreach ( $pro_tabs as $tab_id => $feature ) { // Guideline 5: never lock a tab whose feature code ships in this edition. $tabs[ $tab_id ] = UXPack_License::is_ui_locked( $feature ); } // Directory Basic: omitted-module tabs are mock/upsell (no Save), not locked built-in code. if ( UXPack_License::is_directory_edition() && class_exists( 'UXPack_Pro_Mocks', false ) && UXPack_Pro_Mocks::is_enabled() ) { foreach ( UXPack_Pro_Mocks::get_mock_settings_tabs() as $mock_tab ) { $tabs[ $mock_tab ] = true; } } return $tabs; } /** * Register settings. */ public function register_settings() { register_setting( 'uxpack_settings', 'uxpack_storage_path', array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_storage_path' ), ) ); register_setting( 'uxpack_settings', 'uxpack_enable_log', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_checkbox' ), 'default' => 1, ) ); register_setting( 'uxpack_settings', 'uxpack_max_backups', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_max_backups' ), 'default' => UXPack_License::is_directory_edition() ? 5 : 0, ) ); register_setting( 'uxpack_settings', 'uxpack_activity_log_per_page', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_activity_log_per_page' ), 'default' => 25, ) ); register_setting( 'uxpack_settings', 'uxpack_backup_compression', array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_backup_compression' ), 'default' => 'store', ) ); // Features that ship fully in Basic (Guideline 5). register_setting( 'uxpack_settings', 'uxpack_email_after_backup', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_checkbox' ), 'default' => 0, ) ); register_setting( 'uxpack_settings', 'uxpack_email_after_backup_recipient', array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_email_recipient' ), 'default' => '', ) ); register_setting( 'uxpack_settings', 'uxpack_email_on_backup_failure', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_checkbox' ), 'default' => 0, ) ); register_setting( 'uxpack_settings', 'uxpack_email_on_restore_success', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_checkbox' ), 'default' => 0, ) ); register_setting( 'uxpack_settings', 'uxpack_email_on_restore_failure', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_checkbox' ), 'default' => 0, ) ); register_setting( 'uxpack_settings', 'uxpack_exclude_paths', array( 'type' => 'string', 'sanitize_callback' => array( $this, 'sanitize_exclude_paths' ), 'default' => '', ) ); register_setting( 'uxpack_settings', 'uxpack_health_warnings_enabled', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_health_warnings_enabled' ), 'default' => 1, ) ); register_setting( 'uxpack_settings', 'uxpack_health_min_disk_mb', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_health_min_disk_mb' ), 'default' => 500, ) ); register_setting( 'uxpack_settings', 'uxpack_health_stale_days', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_health_stale_days' ), 'default' => 7, ) ); register_setting( 'uxpack_settings', 'uxpack_restore_verify_before', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_checkbox' ), 'default' => 0, ) ); register_setting( 'uxpack_settings', 'uxpack_auto_verify_after_backup', array( 'type' => 'integer', 'sanitize_callback' => array( $this, 'sanitize_checkbox' ), 'default' => 0, ) ); if ( class_exists( 'UXPack_Preflight', false ) ) { register_setting( 'uxpack_settings', UXPack_Preflight::OPTION_BLOCK_ON_FAIL, array( 'type' => 'integer', 'sanitize_callback' => array( 'UXPack_Preflight', 'sanitize_checkbox' ), 'default' => 0, ) ); } if ( class_exists( 'UXPack_Admin_Pro', false ) ) { UXPack_Admin_Pro::instance()->register_settings(); } } /** * Map of UXPack settings option names to sanitize callbacks. * * @return array */ public function get_settings_sanitizers() { $map = array( 'uxpack_storage_path' => array( $this, 'sanitize_storage_path' ), 'uxpack_enable_log' => array( $this, 'sanitize_checkbox' ), 'uxpack_max_backups' => array( $this, 'sanitize_max_backups' ), 'uxpack_activity_log_per_page' => array( $this, 'sanitize_activity_log_per_page' ), 'uxpack_backup_compression' => array( $this, 'sanitize_backup_compression' ), 'uxpack_email_after_backup' => array( $this, 'sanitize_checkbox' ), 'uxpack_email_after_backup_recipient' => array( $this, 'sanitize_email_recipient' ), 'uxpack_email_on_backup_failure' => array( $this, 'sanitize_checkbox' ), 'uxpack_email_on_restore_success' => array( $this, 'sanitize_checkbox' ), 'uxpack_email_on_restore_failure' => array( $this, 'sanitize_checkbox' ), 'uxpack_exclude_paths' => array( $this, 'sanitize_exclude_paths' ), 'uxpack_health_warnings_enabled' => array( $this, 'sanitize_health_warnings_enabled' ), 'uxpack_health_min_disk_mb' => array( $this, 'sanitize_health_min_disk_mb' ), 'uxpack_health_stale_days' => array( $this, 'sanitize_health_stale_days' ), 'uxpack_restore_verify_before' => array( $this, 'sanitize_checkbox' ), 'uxpack_auto_verify_after_backup' => array( $this, 'sanitize_checkbox' ), ); if ( class_exists( 'UXPack_Preflight', false ) ) { $map[ UXPack_Preflight::OPTION_BLOCK_ON_FAIL ] = array( 'UXPack_Preflight', 'sanitize_checkbox' ); } if ( class_exists( 'UXPack_Admin_Pro', false ) ) { $map = array_merge( $map, UXPack_Admin_Pro::instance()->get_settings_sanitizers() ); } return $map; } /** * Save UXPack settings from a request payload (same fields as the settings form). * * @param array $input Raw input (typically $_POST). * @return true|WP_Error */ public function save_settings_from_input( $input ) { if ( ! is_array( $input ) ) { return new WP_Error( 'uxpack_settings', __( 'Invalid settings payload.', 'uxpack-basic' ) ); } $remote_option_keys = array(); if ( class_exists( 'UXPack_Remote_Storage', false ) ) { $remote_option_keys = array_fill_keys( array_keys( UXPack_Remote_Storage::get_settings_sanitizers() ), true ); } foreach ( $this->get_settings_sanitizers() as $option_name => $sanitizer ) { if ( ! array_key_exists( $option_name, $input ) ) { continue; } // Remote provider options use the license-gated persist path below (Pro module). if ( isset( $remote_option_keys[ $option_name ] ) ) { continue; } $raw = wp_unslash( $input[ $option_name ] ); if ( ! is_callable( $sanitizer ) ) { continue; } $value = call_user_func( $sanitizer, $raw ); $value = UXPack_License::clamp_setting_value( $option_name, $value ); update_option( $option_name, $value ); } if ( class_exists( 'UXPack_Remote_Storage', false ) ) { UXPack_Remote_Storage::save_settings_from_input( $input ); } if ( array_key_exists( UXPack_License::OPTION_EMAIL, $input ) || array_key_exists( UXPack_License::OPTION_KEY, $input ) ) { UXPack_License::refresh_from_stored_credentials(); } return true; } /** * AJAX: Save UXPack settings without a full page reload. */ public function ajax_save_settings() { check_ajax_referer( 'uxpack_settings-options', '_wpnonce' ); if ( ! UXPack_Capabilities::current_user_can( 'manage_settings' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } $result = $this->save_settings_from_input( $_POST ); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } $payload = array( 'message' => __( 'Settings saved.', 'uxpack-basic' ), 'license' => array( 'tier' => UXPack_License::get_tier(), 'tierLabel' => UXPack_License::get_tier_badge_label(), 'status' => UXPack_License::get_status(), 'statusLabel' => UXPack_License::get_status_label(), 'showStatusLabel' => UXPack_License::should_display_status_label(), 'message' => UXPack_License::get_status_message_for_display(), 'messageTone' => UXPack_License::get_status_message_tone(), 'isPro' => UXPack_License::is_pro(), 'activationUsage' => UXPack_License::get_activation_usage_label(), 'showActivationUsage' => UXPack_License::should_display_activation_usage(), 'activationCount' => UXPack_License::get_activation_count(), 'maxActivations' => UXPack_License::get_max_activations(), ), 'menu' => array( 'activityLog' => $this->get_activity_log_menu_payload(), ), ); if ( class_exists( 'UXPack_Remote_Storage', false ) ) { $payload['remoteProviders'] = UXPack_Remote_Storage::get_connection_status_payload(); } wp_send_json_success( $payload ); } /** * Payload for syncing the Activity Log admin submenu after settings save. * * @return array{enabled: bool, url: string, label: string} */ private function get_activity_log_menu_payload() { $can_view = UXPack_Capabilities::current_user_can( 'view_log' ); $enabled = $can_view && (int) get_option( 'uxpack_enable_log', 1 ) === 1; return array( 'enabled' => $enabled, 'url' => admin_url( 'admin.php?page=uxpack-log' ), 'label' => __( 'Activity Log', 'uxpack-basic' ), ); } /** * AJAX: Save one schedule (create or update) without a full page reload. */ public function ajax_save_schedule_settings() { check_ajax_referer( 'uxpack_schedule_settings-options', '_wpnonce' ); if ( ! UXPack_Capabilities::current_user_can( 'manage_schedule' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } $schedule = new UXPack_Schedule(); $result = $schedule->save_schedule_from_input( $_POST ); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } wp_send_json_success( array( 'message' => __( 'Schedule saved.', 'uxpack-basic' ), 'overview' => UXPack_Schedule::get_schedules_overview_payload(), 'schedule' => $result, ) ); } /** * AJAX: Delete a schedule. */ public function ajax_delete_schedule() { check_ajax_referer( 'uxpack_schedule_settings-options', '_wpnonce' ); if ( ! UXPack_Capabilities::current_user_can( 'manage_schedule' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } $id = isset( $_POST['schedule_id'] ) ? sanitize_key( wp_unslash( $_POST['schedule_id'] ) ) : ''; $schedule = new UXPack_Schedule(); $result = $schedule->delete_schedule( $id ); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } wp_send_json_success( array( 'message' => __( 'Schedule deleted.', 'uxpack-basic' ), 'overview' => UXPack_Schedule::get_schedules_overview_payload(), ) ); } /** * Default values for UXPack → Settings options. * * @return array */ public static function get_default_settings() { $defaults = array( 'uxpack_storage_path' => '', 'uxpack_enable_log' => 1, 'uxpack_max_backups' => UXPack_License::is_directory_edition() ? 5 : 0, 'uxpack_activity_log_per_page' => 25, 'uxpack_backup_compression' => 'store', 'uxpack_health_warnings_enabled' => 1, 'uxpack_health_min_disk_mb' => 500, 'uxpack_health_stale_days' => 7, 'uxpack_email_after_backup' => 0, 'uxpack_email_on_backup_failure' => 0, 'uxpack_email_on_restore_success' => 0, 'uxpack_email_on_restore_failure' => 0, 'uxpack_restore_verify_before' => 0, 'uxpack_auto_verify_after_backup' => 0, 'uxpack_email_after_backup_recipient' => '', 'uxpack_exclude_paths' => '', ); if ( class_exists( 'UXPack_Preflight', false ) ) { $defaults[ UXPack_Preflight::OPTION_BLOCK_ON_FAIL ] = 0; } if ( class_exists( 'UXPack_Admin_Pro', false ) ) { $defaults = array_merge( $defaults, UXPack_Admin_Pro::get_default_settings() ); } return $defaults; } /** * Restore UXPack → Settings options to their defaults. */ public static function reset_settings_to_defaults() { foreach ( self::get_default_settings() as $option => $value ) { update_option( $option, $value ); } // Remote OAuth tokens / sealed secrets are not in get_default_settings(); wipe explicitly. // No-op on WordPress.org Basic (UXPack_Remote_Storage omitted from that ZIP). if ( class_exists( 'UXPack_Remote_Storage', false ) ) { UXPack_Remote_Storage::wipe_all_secrets(); } UXPack_Backup::trim_old_backups(); } /** * Settings export file format identifier. */ const SETTINGS_EXPORT_FORMAT = 'uxpack-settings'; /** * Settings export schema version. */ const SETTINGS_EXPORT_VERSION = 1; /** * Option keys included in a settings export. * * @param bool $include_license Whether to include license email and key. * @return list */ public function get_exportable_setting_keys( $include_license = false ) { $keys = array_keys( $this->get_settings_sanitizers() ); $exclude = array(); if ( ! $include_license ) { $exclude[] = UXPack_License::OPTION_EMAIL; $exclude[] = UXPack_License::OPTION_KEY; } if ( class_exists( 'UXPack_Remote_Storage', false ) ) { $exclude = array_merge( $exclude, UXPack_Remote_Storage::get_secret_option_keys() ); } if ( empty( $exclude ) ) { return $keys; } return array_values( array_diff( $keys, $exclude ) ); } /** * Read current UXPack → Settings option values for export. * * @param bool $include_license Whether to include license email and key. * @return array */ public function collect_settings_for_export( $include_license = false ) { $defaults = self::get_default_settings(); $settings = array(); foreach ( $this->get_exportable_setting_keys( $include_license ) as $option_name ) { if ( array_key_exists( $option_name, $defaults ) ) { $settings[ $option_name ] = get_option( $option_name, $defaults[ $option_name ] ); continue; } $settings[ $option_name ] = get_option( $option_name, '' ); } return $settings; } /** * Build a portable settings export payload. * * @param bool $include_license Whether to include license email and key. * @return array */ public function build_settings_export_payload( $include_license = false ) { return array( 'format' => self::SETTINGS_EXPORT_FORMAT, 'version' => self::SETTINGS_EXPORT_VERSION, 'plugin_version' => defined( 'UXPACK_VERSION' ) ? UXPACK_VERSION : '', 'exported_at' => gmdate( 'c' ), 'settings' => $this->collect_settings_for_export( $include_license ), ); } /** * Parse an uploaded settings export file via wp_handle_upload (Plugin Review). * * @param array $file Uploaded file entry from $_FILES. * @return array|WP_Error */ public function parse_settings_import_file( $file ) { if ( ! is_array( $file ) ) { return new WP_Error( 'uxpack_settings_import', __( 'No settings file was uploaded.', 'uxpack-basic' ) ); } if ( ! empty( $file['error'] ) ) { return new WP_Error( 'uxpack_settings_import', __( 'The settings file could not be uploaded.', 'uxpack-basic' ) ); } if ( empty( $file['tmp_name'] ) || ! is_uploaded_file( $file['tmp_name'] ) ) { return new WP_Error( 'uxpack_settings_import', __( 'The uploaded settings file is invalid.', 'uxpack-basic' ) ); } if ( ! function_exists( 'wp_handle_upload' ) ) { require_once ABSPATH . 'wp-admin/includes/file.php'; } $filetype_filter = static function ( $data, $file_path, $filename, $mimes ) { unset( $file_path, $mimes ); $filename = (string) $filename; if ( ! preg_match( '/\.json$/i', $filename ) ) { return $data; } if ( ! is_array( $data ) ) { $data = array(); } $data['ext'] = 'json'; $data['type'] = 'application/json'; return $data; }; add_filter( 'wp_check_filetype_and_ext', $filetype_filter, 10, 4 ); $overrides = array( 'test_form' => false, 'mimes' => array( 'json' => 'application/json', ), ); $uploaded = wp_handle_upload( $file, $overrides ); remove_filter( 'wp_check_filetype_and_ext', $filetype_filter, 10 ); if ( ! is_array( $uploaded ) || ! empty( $uploaded['error'] ) || empty( $uploaded['file'] ) ) { return new WP_Error( 'uxpack_settings_import', __( 'The settings file could not be uploaded.', 'uxpack-basic' ) ); } $uploaded_path = (string) $uploaded['file']; $contents = is_readable( $uploaded_path ) ? file_get_contents( $uploaded_path ) : false; wp_delete_file( $uploaded_path ); return $this->parse_settings_import_contents( $contents ); } /** * Parse settings export JSON contents (after a successful WordPress upload). * * @param string|false $contents Raw file contents. * @return array|WP_Error */ public function parse_settings_import_contents( $contents ) { if ( false === $contents || '' === $contents ) { return new WP_Error( 'uxpack_settings_import', __( 'The settings file is empty.', 'uxpack-basic' ) ); } $payload = json_decode( (string) $contents, true ); if ( ! is_array( $payload ) ) { return new WP_Error( 'uxpack_settings_import', __( 'The settings file is not valid JSON.', 'uxpack-basic' ) ); } if ( ! isset( $payload['format'] ) || self::SETTINGS_EXPORT_FORMAT !== (string) $payload['format'] ) { return new WP_Error( 'uxpack_settings_import', __( 'This file is not a UXPack settings export.', 'uxpack-basic' ) ); } if ( ! isset( $payload['version'] ) || (int) $payload['version'] !== self::SETTINGS_EXPORT_VERSION ) { return new WP_Error( 'uxpack_settings_import', __( 'This settings export uses an unsupported format version.', 'uxpack-basic' ) ); } if ( ! isset( $payload['settings'] ) || ! is_array( $payload['settings'] ) ) { return new WP_Error( 'uxpack_settings_import', __( 'The settings file does not contain any settings.', 'uxpack-basic' ) ); } return $payload; } /** * Apply settings from an export payload. * * @param array $payload Parsed export payload. * @return int|WP_Error Number of options updated. */ public function import_settings_from_payload( $payload ) { if ( ! is_array( $payload ) || ! isset( $payload['settings'] ) || ! is_array( $payload['settings'] ) ) { return new WP_Error( 'uxpack_settings_import', __( 'The settings file does not contain any settings.', 'uxpack-basic' ) ); } $allowed_keys = array_keys( $this->get_settings_sanitizers() ); $input = array(); foreach ( $payload['settings'] as $option_name => $value ) { $option_name = (string) $option_name; if ( ! in_array( $option_name, $allowed_keys, true ) ) { continue; } $input[ $option_name ] = $value; } if ( empty( $input ) ) { return new WP_Error( 'uxpack_settings_import', __( 'No recognized settings were found in the file.', 'uxpack-basic' ) ); } $result = $this->save_settings_from_input( $input ); if ( is_wp_error( $result ) ) { return $result; } UXPack_Backup::trim_old_backups(); return count( $input ); } /** * Run selected reset actions. * * @param bool $delete_settings Reset plugin settings to defaults. * @param bool $delete_storage Delete the backup storage directory. * @return true|WP_Error */ private function run_reset_settings( $delete_settings, $delete_storage ) { if ( ! UXPack_Capabilities::current_user_can( 'manage_settings' ) ) { return new WP_Error( 'uxpack_forbidden', __( 'Permission denied.', 'uxpack-basic' ) ); } if ( ! $delete_settings && ! $delete_storage ) { return new WP_Error( 'uxpack_reset_none', __( 'Please select at least one reset option.', 'uxpack-basic' ) ); } $storage_path = $delete_storage ? UXPack_Backup::get_storage_path() : ''; if ( $delete_settings ) { self::reset_settings_to_defaults(); } if ( $delete_storage && ( '' === $storage_path || ! UXPack_Backup::delete_storage_directory( $storage_path ) ) ) { return new WP_Error( 'uxpack_reset_storage', __( 'The backup storage directory could not be deleted.', 'uxpack-basic' ) ); } return true; } /** * Success message after a reset action. * * @param bool $delete_settings Whether settings were reset. * @param bool $delete_storage Whether storage was deleted. * @return string */ private function get_reset_success_message( $delete_settings, $delete_storage ) { if ( $delete_settings && $delete_storage ) { return __( 'Settings reset to default values and backup storage directory deleted.', 'uxpack-basic' ); } if ( $delete_settings ) { return __( 'Settings reset to default values.', 'uxpack-basic' ); } return __( 'Backup storage directory deleted.', 'uxpack-basic' ); } /** * Reset settings to defaults (admin-post fallback). */ public function handle_reset_settings() { if ( ! UXPack_Capabilities::current_user_can( 'manage_settings' ) ) { wp_die( esc_html__( 'Permission denied.', 'uxpack-basic' ) ); } check_admin_referer( 'uxpack_reset_settings' ); $delete_settings = ! empty( $_POST['uxpack_reset_delete_settings'] ); $delete_storage = ! empty( $_POST['uxpack_reset_delete_storage'] ); $result = $this->run_reset_settings( $delete_settings, $delete_storage ); if ( is_wp_error( $result ) ) { $error_code = $result->get_error_code(); $redirect_code = 'uxpack_reset_storage' === $error_code ? 'storage' : 'none_selected'; wp_safe_redirect( add_query_arg( 'uxpack_settings_reset_error', $redirect_code, admin_url( 'admin.php?page=uxpack-settings#reset' ) ) ); exit; } $redirect_args = array(); if ( $delete_settings ) { $redirect_args['uxpack_settings_reset'] = '1'; } if ( $delete_storage ) { $redirect_args['uxpack_storage_deleted'] = '1'; } wp_safe_redirect( add_query_arg( $redirect_args, admin_url( 'admin.php?page=uxpack-settings#reset' ) ) ); exit; } /** * AJAX: Reset plugin settings and/or backup storage. */ public function ajax_reset_settings() { if ( ! UXPack_Capabilities::current_user_can( 'manage_settings' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ), 403 ); } check_ajax_referer( 'uxpack_backup', 'nonce' ); $delete_settings = ! empty( $_POST['uxpack_reset_delete_settings'] ); $delete_storage = ! empty( $_POST['uxpack_reset_delete_storage'] ); $result = $this->run_reset_settings( $delete_settings, $delete_storage ); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } wp_send_json_success( array( 'message' => $this->get_reset_success_message( $delete_settings, $delete_storage ), 'settingsReset' => (bool) $delete_settings, 'storageDeleted' => (bool) $delete_storage, ) ); } /** * Sanitize storage path. * * @param string $value * @return string */ public function sanitize_storage_path( $value ) { $value = sanitize_text_field( $value ); $value = trim( $value ); if ( empty( $value ) ) { return ''; } $value = rtrim( $value, '/' . DIRECTORY_SEPARATOR ); if ( ! UXPack_Backup::is_allowed_storage_path( $value ) ) { return ''; } $resolved = realpath( $value ); return false !== $resolved ? $resolved : $value; } /** * Sanitize max backups value (0 = unlimited). * * @param mixed $value * @return int */ public function sanitize_max_backups( $value ) { $value = absint( $value ); // WordPress.org (directory) edition: no artificial cap (0 = unlimited). if ( UXPack_License::is_directory_edition() ) { return max( 0, $value ); } if ( UXPack_License::is_basic() && defined( 'UXPack_License::BASIC_MAX_BACKUPS_CAP' ) ) { if ( $value <= 0 || $value > UXPack_License::BASIC_MAX_BACKUPS_CAP ) { return UXPack_License::BASIC_MAX_BACKUPS; } return max( 1, min( UXPack_License::BASIC_MAX_BACKUPS_CAP, $value ) ); } return max( 0, $value ); } /** * Sanitize health warnings enabled toggle. * * @param mixed $value Raw value. * @return int */ public function sanitize_health_warnings_enabled( $value ) { return UXPack_Health::sanitize_enabled( $value ); } /** * Sanitize minimum free disk space for health warnings. * * @param mixed $value Raw value. * @return int */ public function sanitize_health_min_disk_mb( $value ) { return UXPack_Health::sanitize_min_disk_mb( $value ); } /** * Sanitize stale backup threshold for health warnings. * * @param mixed $value Raw value. * @return int */ public function sanitize_health_stale_days( $value ) { return UXPack_Health::sanitize_stale_days( $value ); } /** * Sanitize backup compression setting. * * @param mixed $value Raw value. * @return string store|deflate */ public function sanitize_backup_compression( $value ) { $value = sanitize_key( (string) $value ); return in_array( $value, array( 'store', 'deflate' ), true ) ? $value : 'store'; } /** * Sanitize Activity Log entries per page (5–100). * * @param mixed $value * @return int */ public function sanitize_activity_log_per_page( $value ) { $value = absint( $value ); if ( $value < 5 ) { $value = 5; } if ( $value > 100 ) { $value = 100; } return $value; } /** * Sanitize exclude paths from the folder tree (array) or legacy textarea (string). * * @param mixed $value Submitted paths. * @return string */ public function sanitize_exclude_paths( $value ) { $paths = array(); if ( is_array( $value ) ) { foreach ( $value as $line ) { $paths[] = (string) $line; } } elseif ( is_string( $value ) ) { $paths = preg_split( '/\r\n|\r|\n/', $value ); } return implode( "\n", self::normalize_exclude_paths_list( $paths ) ); } /** * Parse stored exclude paths into a validated list. * * @param mixed $raw Option value or null to load from the database. * @return string[] */ public static function parse_exclude_paths_option( $raw = null ) { if ( null === $raw ) { $raw = get_option( 'uxpack_exclude_paths', '' ); } $paths = array(); if ( is_array( $raw ) ) { $paths = $raw; } elseif ( is_string( $raw ) && '' !== trim( $raw ) ) { $paths = preg_split( '/\r\n|\r|\n/', $raw ); } return self::normalize_exclude_paths_list( $paths ); } /** * Validate exclude paths and drop redundant child paths when a parent is selected. * * @param string[] $paths Raw path list. * @return string[] */ public static function normalize_exclude_paths_list( $paths ) { $normalized = array(); foreach ( (array) $paths as $line ) { $line = trim( (string) $line ); if ( '' === $line ) { continue; } $line = ltrim( str_replace( '\\', '/', $line ), '/' ); if ( '' === $line || false !== strpos( $line, '..' ) ) { continue; } $normalized[] = sanitize_text_field( $line ); } $normalized = array_values( array_unique( $normalized ) ); if ( empty( $normalized ) ) { return array(); } usort( $normalized, function ( $a, $b ) { return strlen( $a ) - strlen( $b ); } ); $minimal = array(); foreach ( $normalized as $path ) { $skip = false; foreach ( $minimal as $parent ) { if ( $path === $parent || 0 === strpos( $path, $parent . '/' ) ) { $skip = true; break; } } if ( ! $skip ) { $minimal[] = $path; } } return $minimal; } /** * Basenames that are always excluded anywhere in the tree. * * @return string[] */ private static function get_locked_exclude_basenames() { $rules = UXPack_Backup::get_exclude_rules(); return isset( $rules['basenames'] ) && is_array( $rules['basenames'] ) ? array_values( $rules['basenames'] ) : array(); } /** * Paths that are locked because UXPack excludes them automatically. * * Uses logical tree paths (e.g. wp-content/uxpack-backups) so parent * checkboxes can show partial state before those nodes are expanded. * * @return string[] */ private static function get_auto_locked_exclude_paths() { $storage = UXPack_Backup::get_storage_path(); $locked = array(); $storage_norm = self::normalize_absolute_path( $storage ); $storage_real = realpath( $storage ); // Prefer mapping under WP_CONTENT_DIR → logical "wp-content/…" tree path. if ( defined( 'WP_CONTENT_DIR' ) ) { $content_norm = self::normalize_absolute_path( WP_CONTENT_DIR ); $content_real = realpath( WP_CONTENT_DIR ); if ( false !== $content_real && false !== $storage_real ) { $content_prefix = rtrim( $content_real, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR; if ( $storage_real === $content_real ) { $locked[] = 'wp-content'; } elseif ( 0 === strpos( $storage_real, $content_prefix ) ) { $suffix = ltrim( str_replace( '\\', '/', substr( $storage_real, strlen( $content_prefix ) ) ), '/' ); $locked[] = '' === $suffix ? 'wp-content' : 'wp-content/' . $suffix; } } elseif ( '' !== $content_norm && 0 === strpos( $storage_norm . '/', $content_norm . '/' ) ) { // Storage dir may not exist yet. $suffix = ltrim( substr( $storage_norm, strlen( $content_norm ) ), '/' ); $locked[] = '' === $suffix ? 'wp-content' : 'wp-content/' . $suffix; } } // Fallback: path relative to WordPress install root. if ( empty( $locked ) ) { $root_real = self::get_wordpress_root_directory(); if ( false !== $storage_real && false !== $root_real ) { $root_prefix = rtrim( $root_real, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR; if ( 0 === strpos( $storage_real, $root_prefix ) ) { $relative = ltrim( str_replace( '\\', '/', substr( $storage_real, strlen( $root_prefix ) ) ), '/' ); if ( '' !== $relative ) { $locked[] = $relative; } } } else { $root = self::normalize_absolute_path( class_exists( 'UXPack_Backup', false ) ? UXPack_Backup::get_wordpress_install_root() : ( defined( 'ABSPATH' ) ? (string) ABSPATH : '' ) ); if ( '' !== $root && 0 === strpos( $storage_norm . '/', $root . '/' ) ) { $relative = ltrim( substr( $storage_norm, strlen( $root ) ), '/' ); if ( '' !== $relative ) { $locked[] = $relative; } } } } return array_values( array_unique( $locked ) ); } /** * Whether a path is a top-level WordPress system folder. * * @param string $relative_path Path relative to ABSPATH. * @return bool */ public static function is_system_exclude_root_path( $relative_path ) { $relative_path = ltrim( str_replace( '\\', '/', (string) $relative_path ), '/' ); return in_array( $relative_path, self::get_standard_wordpress_root_folders(), true ); } /** * Whether selected exclude paths include WordPress system root folders. * * @param string[] $paths Selected exclude paths. * @return bool */ public static function selected_paths_include_system_roots( $paths ) { $paths = self::normalize_exclude_paths_list( (array) $paths ); foreach ( $paths as $path ) { if ( self::is_system_exclude_root_path( $path ) ) { return true; } } return false; } /** * Whether a folder node is always excluded and cannot be toggled. * * @param string $relative_path Path relative to ABSPATH. * @param string $basename Folder basename. * @return bool */ private static function is_exclude_tree_node_locked( $relative_path, $basename ) { if ( in_array( $basename, self::get_locked_exclude_basenames(), true ) ) { return true; } $relative_path = ltrim( str_replace( '\\', '/', (string) $relative_path ), '/' ); foreach ( self::get_auto_locked_exclude_paths() as $locked_path ) { if ( $relative_path === $locked_path || 0 === strpos( $relative_path, $locked_path . '/' ) ) { return true; } } return false; } /** * Stable checkbox ID for an exclude-tree node. * * @param string $relative_path Path relative to ABSPATH. * @return string */ private static function get_exclude_tree_checkbox_id( $relative_path ) { $relative_path = trim( str_replace( '\\', '/', (string) $relative_path ), '/' ); if ( '' === $relative_path ) { return 'uxpack-exclude-root'; } $parts = explode( '/', $relative_path ); $parts = array_map( static function( $part ) { return preg_replace( '/[^a-zA-Z0-9_-]/', '-', (string) $part ); }, $parts ); return 'uxpack-exclude-' . implode( '__', array_values( array_filter( $parts, 'strlen' ) ) ); } /** * Selected exclude paths plus always-excluded (locked) paths for tree checkbox state. * * @param string[] $selected_paths User-selected exclude paths. * @return string[] */ private static function get_exclude_tree_effective_selected_paths( $selected_paths ) { $paths = self::normalize_exclude_paths_list( (array) $selected_paths ); $paths = array_merge( $paths, self::get_auto_locked_exclude_paths() ); return array_values( array_unique( $paths ) ); } /** * Whether a path is selected or covered by a selected ancestor. * * @param string $relative_path Path relative to ABSPATH. * @param string[] $selected_paths Selected exclude paths. * @return string|false selected|inherited|partial|false */ private static function get_exclude_tree_check_state( $relative_path, $selected_paths ) { $relative_path = ltrim( str_replace( '\\', '/', (string) $relative_path ), '/' ); $selected_paths = self::get_exclude_tree_effective_selected_paths( $selected_paths ); foreach ( $selected_paths as $selected ) { if ( $relative_path === $selected ) { return 'selected'; } if ( 0 === strpos( $relative_path, $selected . '/' ) ) { return 'inherited'; } } foreach ( $selected_paths as $selected ) { if ( 0 === strpos( $selected, $relative_path . '/' ) ) { return 'partial'; } } return false; } /** * WordPress root directory for exclude-path scanning. * * @return string|false */ private static function get_wordpress_root_directory() { if ( class_exists( 'UXPack_Backup', false ) ) { $install = UXPack_Backup::get_wordpress_install_root(); if ( '' !== $install ) { $root = realpath( $install ); if ( false !== $root && is_dir( $root ) ) { return rtrim( $root, '\\/' ); } if ( is_dir( $install ) ) { return $install; } } } if ( defined( 'ABSPATH' ) ) { $root = realpath( ABSPATH ); if ( false !== $root && is_dir( $root ) ) { return rtrim( $root, '\\/' ); } $root = rtrim( ABSPATH, '\\/' ); if ( is_dir( $root ) ) { return $root; } } return false; } /** * Normalize a path for prefix comparisons. * * @param string $path Absolute path. * @return string */ private static function normalize_absolute_path( $path ) { return rtrim( str_replace( '\\', '/', (string) $path ), '/' ); } /** * Resolve an absolute directory from a relative path under ABSPATH. * * @param string $relative_path Path relative to ABSPATH. * @return string|false */ private static function resolve_exclude_tree_directory( $relative_path ) { $relative_path = ltrim( str_replace( '\\', '/', (string) $relative_path ), '/' ); if ( false !== strpos( $relative_path, '..' ) ) { return false; } if ( 0 === strpos( $relative_path, 'wp-content' ) ) { $content_dir = self::get_standard_wordpress_directory_path( 'wp-content' ); if ( false !== $content_dir ) { if ( 'wp-content' === $relative_path ) { return $content_dir; } $suffix = ltrim( substr( $relative_path, strlen( 'wp-content' ) ), '/' ); if ( '' !== $suffix ) { $target = $content_dir . DIRECTORY_SEPARATOR . str_replace( '/', DIRECTORY_SEPARATOR, $suffix ); if ( is_dir( $target ) ) { return $target; } $target_real = realpath( $target ); if ( false !== $target_real && is_dir( $target_real ) ) { return $target_real; } } } } $root_real = self::get_wordpress_root_directory(); if ( false === $root_real ) { return false; } $target = $root_real; if ( '' !== $relative_path ) { $target = $root_real . DIRECTORY_SEPARATOR . str_replace( '/', DIRECTORY_SEPARATOR, $relative_path ); } $target_real = realpath( $target ); if ( false === $target_real || ! is_dir( $target_real ) ) { if ( ! is_dir( $target ) ) { return false; } $target_real = $target; } $root_prefix = self::normalize_absolute_path( $root_real ) . '/'; $target_check = self::normalize_absolute_path( $target_real ); if ( $target_check !== rtrim( $root_prefix, '/' ) && 0 !== strpos( $target_check . '/', $root_prefix ) ) { return false; } return $target_real; } /** * List direct child folders for the exclude-path tree. * * @param string $relative_path Parent path relative to ABSPATH. * @return array */ public static function get_exclude_path_tree_nodes( $relative_path = '' ) { $relative_path = ltrim( str_replace( '\\', '/', (string) $relative_path ), '/' ); $directory = self::resolve_exclude_tree_directory( $relative_path ); if ( false === $directory ) { if ( '' === $relative_path ) { return self::get_fallback_exclude_root_nodes(); } return array(); } $entries = @scandir( $directory ); if ( ! $entries ) { if ( '' === $relative_path ) { return self::get_fallback_exclude_root_nodes(); } return array(); } $nodes = array(); foreach ( $entries as $entry ) { if ( '.' === $entry || '..' === $entry ) { continue; } $full = $directory . DIRECTORY_SEPARATOR . $entry; if ( ! @is_dir( $full ) ) { continue; } $path = ( '' === $relative_path ) ? $entry : $relative_path . '/' . $entry; $has_children = self::exclude_tree_directory_has_subfolders( $full ); $nodes[] = array( 'path' => $path, 'name' => $entry, 'has_children' => $has_children, 'locked' => self::is_exclude_tree_node_locked( $path, $entry ), ); } if ( empty( $nodes ) && '' === $relative_path ) { $nodes = self::get_fallback_exclude_root_nodes(); } if ( '' === $relative_path ) { $nodes = self::ensure_standard_root_exclude_nodes( $nodes ); } usort( $nodes, function ( $a, $b ) { return strcasecmp( $a['name'], $b['name'] ); } ); return $nodes; } /** * Ensure standard WordPress root folders are always present in the tree. * * @param array $nodes Existing nodes. * @return array */ private static function ensure_standard_root_exclude_nodes( $nodes ) { $by_path = array(); foreach ( $nodes as $node ) { $by_path[ $node['path'] ] = $node; } foreach ( self::get_standard_wordpress_root_folders() as $dir ) { if ( isset( $by_path[ $dir ] ) ) { continue; } $full = self::get_standard_wordpress_directory_path( $dir ); $has_children = false; if ( false !== $full ) { $has_children = self::exclude_tree_directory_has_subfolders( $full ); } $by_path[ $dir ] = array( 'path' => $dir, 'name' => $dir, 'has_children' => $has_children || false === $full, 'locked' => self::is_exclude_tree_node_locked( $dir, $dir ), ); } $nodes = array_values( $by_path ); usort( $nodes, function ( $a, $b ) { return strcasecmp( $a['name'], $b['name'] ); } ); return $nodes; } /** * Absolute path for a standard WordPress root folder. * * @param string $relative_path Folder path relative to ABSPATH. * @return string|false */ private static function get_standard_wordpress_directory_path( $relative_path ) { if ( 'wp-content' === $relative_path && defined( 'WP_CONTENT_DIR' ) ) { $content_dir = rtrim( WP_CONTENT_DIR, '\\/' ); if ( is_dir( $content_dir ) ) { return $content_dir; } } $root = self::get_wordpress_root_directory(); if ( false === $root ) { return false; } if ( 'wp-includes' === $relative_path && defined( 'WPINC' ) ) { $includes = $root . DIRECTORY_SEPARATOR . WPINC; if ( is_dir( $includes ) ) { return $includes; } } $path = $root . DIRECTORY_SEPARATOR . str_replace( '/', DIRECTORY_SEPARATOR, $relative_path ); return is_dir( $path ) ? $path : false; } /** * Standard top-level WordPress folders shown in the exclude tree. * * @return string[] */ private static function get_standard_wordpress_root_folders() { return array( 'wp-admin', 'wp-content', 'wp-includes' ); } /** * Fallback root folders when directory scanning is unavailable. * * @return array */ private static function get_fallback_exclude_root_nodes() { $nodes = array(); foreach ( self::get_standard_wordpress_root_folders() as $dir ) { $full = self::get_standard_wordpress_directory_path( $dir ); $has_children = false; if ( false !== $full ) { $has_children = self::exclude_tree_directory_has_subfolders( $full ); } $nodes[] = array( 'path' => $dir, 'name' => $dir, 'has_children' => $has_children || false === $full, 'locked' => self::is_exclude_tree_node_locked( $dir, $dir ), ); } return $nodes; } /** * Whether a directory contains at least one subfolder. * * @param string $directory Absolute directory path. * @return bool */ private static function exclude_tree_directory_has_subfolders( $directory ) { $entries = @scandir( $directory ); if ( ! $entries ) { return false; } foreach ( $entries as $entry ) { if ( '.' === $entry || '..' === $entry ) { continue; } if ( is_dir( $directory . DIRECTORY_SEPARATOR . $entry ) ) { return true; } } return false; } /** * AJAX: Load child folders for the exclude-path tree. */ public function ajax_exclude_tree_children() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'manage_settings' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } $relative_path = isset( $_POST['path'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['path'] ) ) : ''; $selected = array(); if ( isset( $_POST['selected'] ) && is_array( $_POST['selected'] ) ) { $selected = self::normalize_exclude_paths_list( array_map( 'sanitize_text_field', wp_unslash( $_POST['selected'] ) ) ); } $nodes = self::get_exclude_path_tree_nodes( $relative_path ); $payload = array(); foreach ( $nodes as $node ) { $state = self::get_exclude_tree_check_state( $node['path'], $selected ); $payload[] = array( 'path' => $node['path'], 'name' => $node['name'], 'hasChildren' => $node['has_children'], 'locked' => $node['locked'], 'checkState' => $node['locked'] ? 'locked' : ( $state ? $state : 'unchecked' ), 'checkboxId' => self::get_exclude_tree_checkbox_id( $node['path'] ), ); } wp_send_json_success( array( 'nodes' => $payload ) ); } /** * Render one folder node in the exclude-path tree. * * @param array $node Node data. * @param string[] $selected_paths Selected exclude paths. * @param int $depth Nesting depth. * @param int $max_depth Initial server-render depth. */ private function render_exclude_path_tree_node( $node, $selected_paths, $depth = 0, $max_depth = 0 ) { $path = $node['path']; $name = $node['name']; $has_children = ! empty( $node['has_children'] ); $locked = ! empty( $node['locked'] ); $state = $locked ? 'locked' : self::get_exclude_tree_check_state( $path, $selected_paths ); $checked = ( 'selected' === $state || 'inherited' === $state || 'locked' === $state ); $disabled = ( 'inherited' === $state || 'locked' === $state ); $partial = ( 'partial' === $state ); $indent = max( 0, (int) $depth ) * 20; $render_now = $has_children && ( $depth + 1 ) < $max_depth; $expanded = $render_now; ?>
  • role="treeitem" aria-expanded="" style="--uxpack-tree-indent: px" >
    />
      > render_exclude_path_tree_list( $path, $selected_paths, $depth + 1, $max_depth ); } ?>
  • '; echo esc_html( sprintf( /* translators: %s: WordPress root directory path */ __( 'No folders found in the WordPress root (%s).', 'uxpack-basic' ), (string) ( self::get_wordpress_root_directory() ? self::get_wordpress_root_directory() : '' ) ) ); echo ''; return; } if ( empty( $nodes ) ) { return; } foreach ( $nodes as $node ) { $this->render_exclude_path_tree_node( $node, $selected_paths, $depth, $max_depth ); } } /** * Render the exclude-path folder tree. * * @param string[] $selected_paths Selected exclude paths. */ private function render_exclude_path_tree( $selected_paths ) { $show_system_warning = self::selected_paths_include_system_roots( $selected_paths ); ?> " />
      render_exclude_path_tree_list( '', $selected_paths, 0, 0 ); ?>
    '', 'class' => '', 'autocomplete' => '', 'placeholder' => '', 'required' => false, 'disabled' => false, ) ); if ( empty( $args['id'] ) ) { return; } $input_class = trim( 'uxpack-password-input ' . $args['class'] ); ?> autocomplete="" placeholder="" required disabled /> $selected Currently selected destination ids. * @return void */ public static function render_destination_checkboxes( $context = 'manual', $selected = null ) { if ( ! class_exists( 'UXPack_Remote_Storage', false ) || ! UXPack_Remote_Storage::should_show_destination_ui() ) { return; } $context = sanitize_key( (string) $context ); if ( ! in_array( $context, array( 'manual', 'schedule' ), true ) ) { $context = 'manual'; } if ( null === $selected ) { $selected = array( 'local' ); } $selected = UXPack_Remote_Storage::sanitize_destinations( $selected ); $items = UXPack_Remote_Storage::get_available_destinations(); $name = ( 'schedule' === $context ) ? 'uxpack_schedule_destinations[]' : 'uxpack_destinations[]'; $fieldset_id = ( 'schedule' === $context ) ? 'uxpack-schedule-destinations' : 'uxpack-backup-destinations'; $panel_id = $fieldset_id . '-panel'; $toggle_id = $fieldset_id . '-toggle'; $storage_url = admin_url( 'admin.php?page=uxpack-settings#storage' ); $summary_labels = array(); $prepared_items = array(); foreach ( $items as $item ) { $id = isset( $item['id'] ) ? (string) $item['id'] : ''; $label = isset( $item['label'] ) ? (string) $item['label'] : $id; $selectable = ! empty( $item['selectable'] ); $reason = isset( $item['reason'] ) ? (string) $item['reason'] : ''; $is_local = ( 'local' === $id ); $checked = $is_local || in_array( $id, $selected, true ); // Local is always kept so the archive remains visible in the Backups list. if ( $is_local ) { $selectable = true; $checked = true; $label = __( 'Local storage', 'uxpack-basic' ); } if ( $checked ) { $summary_labels[] = $label; } $prepared_items[] = array( 'id' => $id, 'label' => $label, 'selectable' => $selectable, 'reason' => $reason, 'is_local' => $is_local, 'checked' => $checked, ); } if ( empty( $summary_labels ) ) { $summary_labels[] = __( 'Local storage', 'uxpack-basic' ); } $summary_text = implode( ', ', $summary_labels ); ?>

    > */ public static function get_page_header_actions_allowed_html() { return array( 'a' => array( 'href' => true, 'class' => true, 'id' => true, 'target' => true, 'rel' => true, 'title' => true, 'aria-label' => true, ), 'button' => array( 'type' => true, 'class' => true, 'id' => true, 'disabled' => true, 'title' => true, 'aria-label' => true, ), 'span' => array( 'class' => true, 'aria-hidden' => true, ), ); } /** * Late-escape header action HTML for admin page headers. * * @param string $actions Markup from callers. * @return string */ public static function kses_page_header_actions( $actions ) { return wp_kses( (string) $actions, self::get_page_header_actions_allowed_html() ); } /** * Render page header title. * * @param string $title Page title. * @param string $actions Optional HTML for header actions (top right). */ public function render_page_header( $title, $actions = '' ) { $title = trim( (string) $title ); $heading = $title; $tier_slug = ''; $tier_label = ''; $basic_label = __( 'Basic', 'uxpack-basic' ); $pro_label = __( 'Pro', 'uxpack-basic' ); $tier_pattern = '/^(.*)\s+(' . preg_quote( $basic_label, '/' ) . '|' . preg_quote( $pro_label, '/' ) . '|Basic|Pro)$/iu'; if ( preg_match( $tier_pattern, $title, $matches ) ) { $heading = trim( (string) $matches[1] ); $tier_raw = (string) $matches[2]; $tier_slug = ( 0 === strcasecmp( $tier_raw, $pro_label ) || 0 === strcasecmp( $tier_raw, 'Pro' ) ) ? 'pro' : 'basic'; $tier_label = ( 'pro' === $tier_slug ) ? $pro_label : $basic_label; } elseif ( 0 === strcasecmp( $title, $basic_label ) || 0 === strcasecmp( $title, 'Basic' ) ) { $heading = ''; $tier_slug = 'basic'; $tier_label = $basic_label; } elseif ( 0 === strcasecmp( $title, $pro_label ) || 0 === strcasecmp( $title, 'Pro' ) ) { $heading = ''; $tier_slug = 'pro'; $tier_label = $pro_label; } ?>

    render_global_backup_progress(); ?>
    > $members Ordered chain members (base first). * @param string $chain_id Stable chain id for accordion. * @param string $stripe odd|even stripe class suffix. */ private function render_backup_chain_header_row( array $members, $chain_id, $stripe = 'odd' ) { $member_count = count( $members ); if ( $member_count < 2 || '' === $chain_id ) { return; } $latest = end( $members ); if ( ! is_array( $latest ) || empty( $latest['filename'] ) ) { return; } $latest_label = (string) $latest['filename']; $stripe = ( 'even' === $stripe ) ? 'even' : 'odd'; $backup_type_slug = UXPack_Backup::get_backup_type_pill_slug( $latest ); $backup_type_short = UXPack_Backup::format_backup_type_short_label( $latest ); $created_fmt = isset( $latest['created_fmt'] ) ? (string) $latest['created_fmt'] : ''; $size = isset( $latest['size'] ) ? (int) $latest['size'] : 0; $is_encrypted = ! empty( $latest['manifest']['encrypted'] ); $is_locked = UXPack_Backup::is_backup_locked( $latest ); $backup_label = UXPack_Backup::get_backup_label( $latest ); ?>
    render_chain_package_download_button( $latest_label ); ?>
    $backup Backup entry. * @param int $position Zero-based position in chain. * @param int $member_count Total members in chain. * @param string $chain_id Stable chain id for accordion. * @return array */ private function build_backup_chain_row_context( $backup, $position, $member_count, $chain_id = '' ) { $chain_index = class_exists( 'UXPack_Delta', false ) ? UXPack_Delta::get_backup_chain_index( $backup ) : 0; $is_base = 0 === $position; $chain_step = $is_base ? 1 : ( $chain_index > 0 ? $chain_index + 1 : $position + 1 ); return array( 'chain_id' => sanitize_key( (string) $chain_id ), 'chain_depth' => $is_base ? 0 : 1, 'chain_step' => $chain_step, 'chain_member_count' => $member_count, 'chain_is_base' => $is_base, 'chain_is_tip' => ( $position + 1 ) === $member_count, 'chain_marker' => $is_base ? 'base' : ( ( $position + 1 ) === $member_count ? 'tip' : 'branch' ), ); } /** * Render a single backup table row. * * @param array $backup Backup entry from UXPack_Backup::get_backups(). * @param array $display_context Optional chain display context. */ private function render_backup_table_row( $backup, $display_context = array() ) { $is_db_only = ( 0 === strpos( $backup['filename'], 'uxpack-db-' ) ); $can_download_installer = ! $is_db_only; $can_verify = UXPack_Capabilities::current_user_can( 'view_backups' ) && UXPack_License::should_expose_feature_ui( UXPack_License::FEATURE_VERIFY ); $can_edit_label = UXPack_Capabilities::current_user_can( 'run_backups' ); $can_toggle_lock = UXPack_Capabilities::current_user_can( 'run_backups' ) && UXPack_License::should_expose_feature_ui( UXPack_License::FEATURE_BACKUP_LOCK ); $can_delete = UXPack_Capabilities::current_user_can( 'delete_backups' ); $backup_label = UXPack_Backup::get_backup_label( $backup ); $is_locked = UXPack_Backup::is_backup_locked( $backup ); $is_encrypted = ! empty( $backup['manifest']['encrypted'] ); $detail_rows = UXPack_Backup::get_backup_manifest_detail_rows( $backup ); $backup_type_slug = UXPack_Backup::get_backup_type_pill_slug( $backup ); $backup_type_short = UXPack_Backup::format_backup_type_short_label( $backup ); $chain_step = isset( $display_context['chain_step'] ) ? max( 1, (int) $display_context['chain_step'] ) : 0; $chain_is_base = ! empty( $display_context['chain_is_base'] ); $chain_is_tip = ! empty( $display_context['chain_is_tip'] ); $chain_member_count = isset( $display_context['chain_member_count'] ) ? max( 0, (int) $display_context['chain_member_count'] ) : 0; $in_chain = $chain_member_count > 1 && $chain_step > 0; $chain_marker = isset( $display_context['chain_marker'] ) ? sanitize_key( (string) $display_context['chain_marker'] ) : ''; $chain_id = isset( $display_context['chain_id'] ) ? sanitize_key( (string) $display_context['chain_id'] ) : ''; $stripe = ( isset( $display_context['stripe'] ) && 'even' === $display_context['stripe'] ) ? 'even' : 'odd'; $row_classes = array( 'uxpack-backup-row', 'uxpack-backup-row--' . $stripe ); $row_hidden = false; if ( $in_chain ) { $row_classes[] = 'uxpack-backup-row--chain-member'; $row_classes[] = 'uxpack-backup-row--chain-collapsible'; $row_hidden = true; if ( $chain_is_base ) { $row_classes[] = 'uxpack-backup-row--chain-base'; } if ( $chain_is_tip ) { $row_classes[] = 'uxpack-backup-row--chain-tip'; } if ( in_array( $chain_marker, array( 'base', 'branch', 'tip' ), true ) ) { $row_classes[] = 'uxpack-backup-row--chain-marker-' . $chain_marker; } } $row_attrs = array(); if ( ! empty( $row_classes ) ) { $row_attrs['class'] = implode( ' ', $row_classes ); } if ( '' !== $chain_id ) { $row_attrs['data-uxpack-chain-id'] = $chain_id; } if ( $row_hidden ) { $row_attrs['hidden'] = 'hidden'; } ?> $attr_value ) { if ( 'hidden' === $attr_name ) { echo ' hidden'; continue; } printf( ' %s="%s"', esc_attr( $attr_name ), esc_attr( $attr_value ) ); } ?>>
    >

    'standalone', 'backup' => $backup, ); } } ?>
    render_backup_chain_header_row( $members, $chain_id, $chain_stripe ); ?> = 0; $display_index-- ) : $member = $members[ $display_index ]; $chain_context = $this->build_backup_chain_row_context( $member, $display_index, $member_count, $chain_id ); $chain_context['stripe'] = $chain_stripe; $this->render_backup_table_row( $member, $chain_context ); endfor; ++$stripe_index; ?> render_backup_table_row( $list_item['backup'], array( 'stripe' => ( 0 === ( $stripe_index % 2 ) ) ? 'odd' : 'even', ) ); ++$stripe_index; ?>
    render_backup_list( $backups ); return (string) ob_get_clean(); } /** * Render modal shell for backup manifest details. */ private function render_backup_details_modal() { ?> ensure_backup_installers( $backups ); ?>
    render_page_header( UXPack_License::get_admin_menu_title() ); ?>
    render_manual_backup_password_fields(); } ?>
    render_bulk_delete_toolbar( ! empty( $backups ) ); ?>
    render_backup_list( $backups ); ?>
    render_backup_details_modal(); ?> render_verify_modal(); ?> render_page_footer(); ?>
    __( 'Permission denied.', 'uxpack-basic' ) ) ); } $backups = UXPack_Backup::get_backups(); $this->ensure_backup_installers( $backups ); wp_send_json_success( array( 'has_backups' => ! empty( $backups ), 'html' => $this->get_backup_list_html( $backups ), ) ); } /** * AJAX: Update a backup label (Basic + Pro — Guideline 5). */ public function ajax_update_backup_label() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'run_backups' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } $filename = isset( $_POST['filename'] ) ? sanitize_file_name( wp_unslash( $_POST['filename'] ) ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized via UXPack_Backup::sanitize_backup_label(). $label = isset( $_POST['label'] ) ? UXPack_Backup::sanitize_backup_label( wp_unslash( $_POST['label'] ) ) : ''; if ( empty( $filename ) || ! UXPack_Backup::is_valid_backup_filename( $filename ) ) { wp_send_json_error( array( 'message' => __( 'Invalid filename.', 'uxpack-basic' ) ) ); } if ( ! UXPack_Backup::update_backup_manifest_fields( $filename, array( 'label' => $label ) ) ) { wp_send_json_error( array( 'message' => __( 'Could not save label.', 'uxpack-basic' ) ) ); } wp_send_json_success( array( 'message' => __( 'Label saved.', 'uxpack-basic' ), 'label' => $label, 'filename' => $filename, ) ); } /** * AJAX: Return current Activity Log HTML for live UI updates. */ public function ajax_activity_log() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'view_log' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } $current_page = isset( $_POST['paged'] ) ? (int) $_POST['paged'] : 1; $backup_log = self::get_activity_log_entries(); $filters = self::get_activity_log_filters_from_request( 'POST' ); $log_page = self::get_paginated_activity_log( $backup_log, $current_page, $filters ); wp_send_json_success( array( 'html' => $this->get_activity_log_body_html( $log_page['current_page'], $filters ), 'revision' => self::get_activity_log_revision( $backup_log ), 'current_page' => $log_page['current_page'], 'total' => $log_page['total'], 'total_unfiltered' => $log_page['total_unfiltered'], 'filters_active' => self::activity_log_has_active_filters( $filters ), ) ); } /** * Fingerprint for Activity Log polling (skip DOM updates when unchanged). * * @param array|null $backup_log Raw log option value. * @return string */ public static function get_activity_log_revision( $backup_log = null ) { if ( null === $backup_log ) { $backup_log = self::get_activity_log_entries(); } if ( ! is_array( $backup_log ) || empty( $backup_log ) ) { return '0'; } $last = $backup_log[ count( $backup_log ) - 1 ]; if ( ! is_array( $last ) ) { return (string) count( $backup_log ); } $payload = implode( '|', array( isset( $last['time'] ) ? (string) (int) $last['time'] : '', isset( $last['type'] ) ? (string) $last['type'] : '', isset( $last['message'] ) ? (string) $last['message'] : '', isset( $last['filename'] ) ? (string) $last['filename'] : '', ) ); return count( $backup_log ) . ':' . md5( $payload ); } /** * Activity Log table HTML for AJAX refresh. * * @param int $current_page 1-based page number. * @return string */ private function get_activity_log_body_html( $current_page = 1, $filters = array() ) { ob_start(); $this->render_activity_log_body( $current_page, $filters ); return (string) ob_get_clean(); } /** * Read Activity Log filter values from a request superglobal. * * @param string $source 'GET' or 'POST'. * @return array{status: string, search: string, backup: string} */ public static function get_activity_log_filters_from_request( $source = 'GET' ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing -- read-only filter helper; callers enforce caps/nonce. $input = 'POST' === strtoupper( $source ) ? $_POST : $_GET; $backup_log = self::get_activity_log_entries(); $allowed = self::get_activity_log_backup_filenames( $backup_log ); return array( 'status' => isset( $input['log_status'] ) ? self::sanitize_activity_log_status_filter( wp_unslash( $input['log_status'] ) ) : '', 'search' => isset( $input['log_search'] ) ? self::sanitize_activity_log_search_filter( wp_unslash( $input['log_search'] ) ) : '', 'backup' => isset( $input['log_backup'] ) ? self::sanitize_activity_log_backup_filter( wp_unslash( $input['log_backup'] ), $allowed ) : '', ); } /** * Whether any Activity Log filters are active. * * @param array{status?: string, search?: string, backup?: string} $filters Filters. * @return bool */ public static function activity_log_has_active_filters( $filters ) { if ( ! is_array( $filters ) ) { return false; } return '' !== ( $filters['status'] ?? '' ) || '' !== ( $filters['search'] ?? '' ) || '' !== ( $filters['backup'] ?? '' ); } /** * Backup ZIP filenames referenced by one Activity Log entry (field + message). * * @param mixed $entry Log entry. * @return string[] */ public static function get_activity_log_entry_referenced_filenames( $entry ) { if ( ! is_array( $entry ) ) { return array(); } $files = array(); if ( ! empty( $entry['filename'] ) ) { $filename = sanitize_file_name( (string) $entry['filename'] ); if ( '' !== $filename ) { $files[ $filename ] = true; } } $message = isset( $entry['message'] ) ? (string) $entry['message'] : ''; if ( '' !== $message && preg_match_all( '/\b(uxpack[-\w.]+\.zip)\b/i', $message, $matches ) ) { foreach ( $matches[1] as $match ) { $filename = sanitize_file_name( (string) $match ); if ( '' !== $filename ) { $files[ $filename ] = true; } } } return array_keys( $files ); } /** * Map each log index to owning backup ZIP(s). * * Step entries without a filename belong to the next anchoring entry * (success/error that references a ZIP), so deleting a backup removes its * whole run — not only the final success row. * * @param array $backup_log Raw log option value. * @return array Index => filenames (empty = unowned / keep). */ public static function map_activity_log_entry_owners( $backup_log ) { if ( ! is_array( $backup_log ) ) { return array(); } $entries = array(); foreach ( $backup_log as $entry ) { if ( is_array( $entry ) ) { $entries[] = $entry; } } $count = count( $entries ); $owners = array_fill( 0, $count, array() ); $run_start = 0; for ( $i = 0; $i < $count; $i++ ) { $refs = self::get_activity_log_entry_referenced_filenames( $entries[ $i ] ); if ( empty( $refs ) ) { continue; } for ( $j = $run_start; $j <= $i; $j++ ) { $owners[ $j ] = $refs; } $run_start = $i + 1; } return $owners; } /** * Drop Activity Log entries that belong to a deleted backup ZIP (including preceding steps). * * @param array $backup_log Raw log option value. * @param string $filename Backup ZIP basename. * @return array */ public static function remove_activity_log_entries_for_filename( $backup_log, $filename ) { $filename = sanitize_file_name( (string) $filename ); if ( '' === $filename || ! is_array( $backup_log ) ) { return is_array( $backup_log ) ? array_values( $backup_log ) : array(); } $entries = array(); foreach ( $backup_log as $entry ) { if ( is_array( $entry ) ) { $entries[] = $entry; } } $owners = self::map_activity_log_entry_owners( $entries ); $kept = array(); foreach ( $entries as $i => $entry ) { if ( in_array( $filename, $owners[ $i ], true ) ) { continue; } $kept[] = $entry; } return array_values( $kept ); } /** * Keep unowned entries and entries owned by at least one existing backup ZIP. * * @param array $backup_log Raw log option value. * @param string[] $existing_filenames Existing backup ZIP basenames. * @return array */ public static function keep_activity_log_entries_for_existing_backups( $backup_log, $existing_filenames ) { if ( ! is_array( $backup_log ) ) { return array(); } $existing = array(); foreach ( (array) $existing_filenames as $name ) { $name = sanitize_file_name( (string) $name ); if ( '' !== $name ) { $existing[ $name ] = true; } } $entries = array(); foreach ( $backup_log as $entry ) { if ( is_array( $entry ) ) { $entries[] = $entry; } } $owners = self::map_activity_log_entry_owners( $entries ); $kept = array(); foreach ( $entries as $i => $entry ) { $entry_owners = $owners[ $i ]; if ( empty( $entry_owners ) ) { $kept[] = $entry; continue; } foreach ( $entry_owners as $owner ) { if ( isset( $existing[ $owner ] ) ) { $kept[] = $entry; continue 2; } } } return self::strip_trailing_unowned_activity_log_steps( $kept ); } /** * Remove leftover step rows after a success entry was already pruned (incomplete cleanup). * Skipped while a backup is running so live progress stays visible. * * @param array $entries Log entries (oldest first). * @return array */ public static function strip_trailing_unowned_activity_log_steps( $entries ) { if ( ! is_array( $entries ) || empty( $entries ) ) { return array(); } $state = get_option( 'uxpack_backup_state', array() ); if ( is_array( $state ) && isset( $state['status'] ) && 'running' === $state['status'] ) { return array_values( $entries ); } $entries = array_values( $entries ); while ( ! empty( $entries ) ) { $last = $entries[ count( $entries ) - 1 ]; if ( ! is_array( $last ) ) { array_pop( $entries ); continue; } if ( ! empty( self::get_activity_log_entry_referenced_filenames( $last ) ) ) { break; } $type = isset( $last['type'] ) ? (string) $last['type'] : ''; if ( 'step' !== $type ) { break; } $message = isset( $last['message'] ) ? (string) $last['message'] : ''; if ( preg_match( '/^Retention deleted /i', $message ) ) { break; } array_pop( $entries ); } return array_values( $entries ); } /** * Persist Activity Log without entries for a deleted backup ZIP. * * @param string $filename Backup ZIP basename. */ public static function prune_activity_log_for_filename( $filename ) { $filename = sanitize_file_name( (string) $filename ); if ( '' === $filename ) { return; } $log = get_option( 'uxpack_error_log', array() ); if ( ! is_array( $log ) || empty( $log ) ) { return; } $pruned = self::remove_activity_log_entries_for_filename( $log, $filename ); if ( $pruned !== array_values( $log ) ) { update_option( 'uxpack_error_log', $pruned, false ); } } /** * Load Activity Log and drop entries for backups that no longer exist on disk. * * @return array */ public static function get_activity_log_entries() { $log = get_option( 'uxpack_error_log', array() ); if ( ! is_array( $log ) ) { return array(); } if ( empty( $log ) ) { return array(); } $existing = array(); if ( class_exists( 'UXPack_Backup' ) ) { foreach ( UXPack_Backup::get_backups() as $backup ) { if ( empty( $backup['filename'] ) ) { continue; } $name = sanitize_file_name( (string) $backup['filename'] ); if ( '' !== $name ) { $existing[] = $name; } } } $pruned = self::keep_activity_log_entries_for_existing_backups( $log, $existing ); if ( $pruned !== array_values( $log ) ) { update_option( 'uxpack_error_log', $pruned, false ); } return $pruned; } /** * Unique backup filenames referenced in the Activity Log (newest first). * * @param array $backup_log Raw log option value. * @return string[] */ public static function get_activity_log_backup_filenames( $backup_log ) { if ( ! is_array( $backup_log ) || empty( $backup_log ) ) { return array(); } $files = array(); foreach ( $backup_log as $entry ) { if ( ! is_array( $entry ) ) { continue; } $time = isset( $entry['time'] ) ? (int) $entry['time'] : 0; foreach ( self::get_activity_log_entry_referenced_filenames( $entry ) as $filename ) { $files[ $filename ] = isset( $files[ $filename ] ) ? max( $files[ $filename ], $time ) : $time; } } if ( empty( $files ) ) { return array(); } arsort( $files, SORT_NUMERIC ); return array_keys( $files ); } /** * @param mixed $backup Raw backup filename filter. * @param string[] $allowed Allowed filenames from the log. * @return string */ public static function sanitize_activity_log_backup_filter( $backup, $allowed = array() ) { $backup = sanitize_file_name( (string) $backup ); if ( '' === $backup ) { return ''; } if ( ! empty( $allowed ) && ! in_array( $backup, $allowed, true ) ) { return ''; } return $backup; } /** * Allowed Activity Log status filter values (empty string = all). * * @return array Status slug => label. */ public static function get_activity_log_status_filter_options() { return array( '' => __( 'All statuses', 'uxpack-basic' ), 'step' => __( 'Step', 'uxpack-basic' ), 'success' => __( 'Success', 'uxpack-basic' ), 'error' => __( 'Error', 'uxpack-basic' ), ); } /** * @param mixed $status Raw status filter. * @return string Empty string or one of step, success, error. */ public static function sanitize_activity_log_status_filter( $status ) { $status = sanitize_key( (string) $status ); $allowed = array( 'step', 'success', 'error' ); return in_array( $status, $allowed, true ) ? $status : ''; } /** * @param mixed $search Raw search string. * @return string */ public static function sanitize_activity_log_search_filter( $search ) { $search = sanitize_text_field( (string) $search ); if ( strlen( $search ) > 200 ) { $search = substr( $search, 0, 200 ); } return $search; } /** * Searchable text for one Activity Log entry (message, file, status, displayed time). * * Time uses the same `Y-m-d H:i:s` format as the Time column so pasting a * timestamp from the table into Search finds the row. * * @param array $entry Log entry. * @return string Lowercase haystack. */ public static function get_activity_log_entry_search_haystack( $entry ) { if ( ! is_array( $entry ) ) { return ''; } $entry_type = isset( $entry['type'] ) ? (string) $entry['type'] : 'error'; $status = 'success' === $entry_type ? __( 'Success', 'uxpack-basic' ) : ( 'step' === $entry_type ? __( 'Step', 'uxpack-basic' ) : __( 'Error', 'uxpack-basic' ) ); $timestamp = isset( $entry['time'] ) ? (int) $entry['time'] : 0; $time_str = $timestamp > 0 ? date_i18n( 'Y-m-d H:i:s', $timestamp ) : ''; return strtolower( ( isset( $entry['message'] ) ? (string) $entry['message'] : '' ) . ' ' . ( isset( $entry['filename'] ) ? (string) $entry['filename'] : '' ) . ' ' . $status . ' ' . $time_str ); } /** * Filter Activity Log entries by status, backup filename, and/or message search. * * Backup filter uses run ownership: preceding steps without a filename belong * to the next success/error that references that ZIP (same as prune logic). * * @param array $backup_log Raw log option value. * @param array $filters Optional filters: status, search, backup. * @return array */ public static function filter_activity_log_entries( $backup_log, $filters = array() ) { if ( ! is_array( $backup_log ) || empty( $backup_log ) ) { return array(); } $filters = wp_parse_args( is_array( $filters ) ? $filters : array(), array( 'status' => '', 'search' => '', 'backup' => '', ) ); $status = self::sanitize_activity_log_status_filter( $filters['status'] ); $search = self::sanitize_activity_log_search_filter( $filters['search'] ); $backup = sanitize_file_name( (string) $filters['backup'] ); $search_lc = '' !== $search ? strtolower( $search ) : ''; $backup_lc = '' !== $backup ? strtolower( $backup ) : ''; $entries = array(); foreach ( $backup_log as $entry ) { if ( is_array( $entry ) ) { $entries[] = $entry; } } $owners = '' !== $backup_lc ? self::map_activity_log_entry_owners( $entries ) : array(); $filtered = array(); foreach ( $entries as $i => $entry ) { if ( '' !== $status ) { $entry_type = isset( $entry['type'] ) ? (string) $entry['type'] : 'error'; if ( $entry_type !== $status ) { continue; } } if ( '' !== $backup_lc ) { $owned = false; foreach ( $owners[ $i ] as $owner ) { if ( strtolower( (string) $owner ) === $backup_lc ) { $owned = true; break; } } if ( ! $owned ) { continue; } } if ( '' !== $search_lc ) { $haystack = self::get_activity_log_entry_search_haystack( $entry ); if ( false === strpos( $haystack, $search_lc ) ) { continue; } } $filtered[] = $entry; } return $filtered; } /** * Human-readable summary when filters are active. * * @param int $total Filtered entry count. * @param int $total_unfiltered Total entries in the log. * @return string */ public static function get_activity_log_filter_summary( $total, $total_unfiltered ) { return sprintf( /* translators: 1: filtered count, 2: total log entries */ __( 'Showing %1$s of %2$s entries.', 'uxpack-basic' ), number_format_i18n( (int) $total ), number_format_i18n( (int) $total_unfiltered ) ); } /** * Render Activity Log filter controls. * * @param array{status: string, search: string, backup: string} $filters Current filters. * @param array $backup_log Raw log entries for backup options. * @param bool $hidden Hide when the log is empty. */ private function render_activity_log_filters( $filters, $backup_log = array(), $hidden = false ) { $status_options = self::get_activity_log_status_filter_options(); $backup_options = self::get_activity_log_backup_filenames( is_array( $backup_log ) ? $backup_log : array() ); $has_filters = self::activity_log_has_active_filters( $filters ); $can_export_log = UXPack_Capabilities::current_user_can( 'view_log' ); $can_clear_log = UXPack_Capabilities::current_user_can( 'clear_log' ); ?>
    >
    '', 'search' => '', 'backup' => '', ) ); $backup_log = self::get_activity_log_entries(); $allowed_backups = self::get_activity_log_backup_filenames( $backup_log ); $filters['status'] = self::sanitize_activity_log_status_filter( $filters['status'] ); $filters['search'] = self::sanitize_activity_log_search_filter( $filters['search'] ); $filters['backup'] = self::sanitize_activity_log_backup_filter( $filters['backup'], $allowed_backups ); $log_page = self::get_paginated_activity_log( $backup_log, $current_page, $filters ); if ( empty( $backup_log ) ) { echo '

    ' . esc_html__( 'No backup log entries yet.', 'uxpack-basic' ) . '

    '; return; } if ( empty( $log_page['entries'] ) ) { if ( self::activity_log_has_active_filters( $filters ) ) { echo '

    ' . esc_html__( 'No entries match the current filters.', 'uxpack-basic' ) . '

    '; } return; } ?> render_activity_log_row( $entry ); ?>
    1 ) : ?> 'uxpack-log', 'paged' => '%#%', ); if ( '' !== $filters['status'] ) { $pagination_args['log_status'] = $filters['status']; } if ( '' !== $filters['search'] ) { $pagination_args['log_search'] = $filters['search']; } if ( '' !== $filters['backup'] ) { $pagination_args['log_backup'] = $filters['backup']; } echo wp_kses_post( paginate_links( array( 'base' => add_query_arg( $pagination_args, admin_url( 'admin.php' ) ), 'format' => '', 'prev_text' => __( '« Previous', 'uxpack-basic' ), 'next_text' => __( 'Next »', 'uxpack-basic' ), 'total' => $log_page['total_pages'], 'current' => $log_page['current_page'], 'type' => 'plain', ) ) ); ?>
    __( 'Permission denied.', 'uxpack-basic' ) ) ); } $run_tick = ! empty( $_POST['run_tick'] ); $result = UXPack_Schedule_Test::run_diagnostics( $run_tick ); wp_send_json_success( $result ); } /** * Entries per page on the Activity Log screen. * * @return int */ public static function get_activity_log_per_page() { $per_page = (int) get_option( 'uxpack_activity_log_per_page', 25 ); $per_page = (int) apply_filters( 'uxpack_activity_log_per_page', $per_page ); if ( $per_page < 5 ) { $per_page = 5; } if ( $per_page > 100 ) { $per_page = 100; } return $per_page; } /** * Maximum Activity Log entries stored in the database. * * @return int */ public static function get_activity_log_max_entries() { $max = (int) apply_filters( 'uxpack_activity_log_max_entries', 500 ); if ( $max < 50 ) { $max = 50; } return $max; } /** * Paginated Activity Log rows (newest first). * * @param array $backup_log Raw log option value. * @param int $current_page 1-based page number. * @return array{entries: array, total: int, per_page: int, current_page: int, total_pages: int} */ public static function get_paginated_activity_log( $backup_log, $current_page = 1, $filters = array() ) { $filters = wp_parse_args( is_array( $filters ) ? $filters : array(), array( 'status' => '', 'search' => '', 'backup' => '', ) ); $allowed_backups = self::get_activity_log_backup_filenames( is_array( $backup_log ) ? $backup_log : array() ); $filters['status'] = self::sanitize_activity_log_status_filter( $filters['status'] ); $filters['search'] = self::sanitize_activity_log_search_filter( $filters['search'] ); $filters['backup'] = self::sanitize_activity_log_backup_filter( $filters['backup'], $allowed_backups ); if ( ! is_array( $backup_log ) || empty( $backup_log ) ) { return array( 'entries' => array(), 'total' => 0, 'total_unfiltered' => 0, 'per_page' => self::get_activity_log_per_page(), 'current_page' => 1, 'total_pages' => 1, 'filters' => $filters, ); } $total_unfiltered = count( $backup_log ); $filtered_log = self::filter_activity_log_entries( $backup_log, $filters ); $per_page = self::get_activity_log_per_page(); $total = count( $filtered_log ); $total_pages = max( 1, (int) ceil( $total / $per_page ) ); $current_page = max( 1, (int) $current_page ); if ( $current_page > $total_pages ) { $current_page = $total_pages; } $offset = ( $current_page - 1 ) * $per_page; $entries = array_slice( array_reverse( $filtered_log ), $offset, $per_page ); return array( 'entries' => $entries, 'total' => $total, 'total_unfiltered' => $total_unfiltered, 'per_page' => $per_page, 'current_page' => $current_page, 'total_pages' => $total_pages, 'filters' => $filters, ); } /** * Render a single Activity Log table row. * * @param array $entry Log entry. */ private function render_activity_log_row( $entry ) { $entry_type = isset( $entry['type'] ) ? $entry['type'] : 'error'; $timestamp = isset( $entry['time'] ) ? (int) $entry['time'] : 0; $date_str = $timestamp > 0 ? date_i18n( 'Y-m-d H:i:s', $timestamp ) : ''; $status_str = ( 'success' === $entry_type ) ? __( 'Success', 'uxpack-basic' ) : ( ( 'step' === $entry_type ) ? __( 'Step', 'uxpack-basic' ) : __( 'Error', 'uxpack-basic' ) ); $message = isset( $entry['message'] ) ? $entry['message'] : ''; if ( ! empty( $entry['filename'] ) ) { $message .= ' ' . $entry['filename']; } ?> 0 || self::activity_log_has_active_filters( $filters ); $filters_active = self::activity_log_has_active_filters( $filters ); ?>
    render_admin_notice( esc_html__( 'Backup log cleared.', 'uxpack-basic' ), 'success', true, true ); ?> render_admin_notice( esc_html__( 'Backup logging is currently disabled in UXPack Settings.', 'uxpack-basic' ), 'warning', true, false ); ?> render_page_header( __( 'Activity Log', 'uxpack-basic' ) ); ?> render_activity_log_filters( $filters, is_array( $backup_log ) ? $backup_log : array(), ! $show_filters ); ?>
    >
    render_activity_log_body( $log_page['current_page'], $filters ); ?>
    render_page_footer(); ?>
    clear_activity_log(); if ( is_wp_error( $result ) ) { wp_die( esc_html( $result->get_error_message() ) ); } wp_safe_redirect( add_query_arg( 'uxpack_log_cleared', '1', admin_url( 'admin.php?page=uxpack-log' ) ) ); exit; } /** * AJAX: Clear the backup log. */ public function ajax_clear_log() { if ( ! UXPack_Capabilities::current_user_can( 'clear_log' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ), 403 ); } check_ajax_referer( 'uxpack_backup', 'nonce' ); $result = $this->clear_activity_log(); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message() ) ); } wp_send_json_success( array( 'message' => __( 'Backup log cleared.', 'uxpack-basic' ), ) ); } /** * Render scheduled backups settings page. */ public function render_schedule_page() { if ( ! UXPack_Capabilities::current_user_can( 'manage_schedule' ) ) { return; } $schedules = UXPack_Schedule::get_schedules(); $defaults = UXPack_Schedule::get_default_schedule(); $can_add = count( $schedules ) < UXPack_Schedule::get_max_schedules(); $show_multiple_schedules = UXPack_License::should_expose_feature_ui( UXPack_License::FEATURE_MULTIPLE_SCHEDULES ); $show_pro_schedule_freqs = UXPack_License::should_expose_feature_ui( UXPack_License::FEATURE_SCHEDULE_WEEKLY_MONTHLY ); $max_schedules = UXPack_Schedule::get_max_schedules(); $overview = UXPack_Schedule::get_schedules_overview_payload(); $has_schedules = ! empty( $schedules ); $active = $has_schedules ? $schedules[0] : $defaults; $weekdays = array( 0 => __( 'Sunday', 'uxpack-basic' ), 1 => __( 'Monday', 'uxpack-basic' ), 2 => __( 'Tuesday', 'uxpack-basic' ), 3 => __( 'Wednesday', 'uxpack-basic' ), 4 => __( 'Thursday', 'uxpack-basic' ), 5 => __( 'Friday', 'uxpack-basic' ), 6 => __( 'Saturday', 'uxpack-basic' ), ); $frequency = $active['frequency']; $time = $active['time']; $weekday = (int) $active['weekday']; $month_day = (int) $active['day']; $backup_type = $active['type']; $enabled = $has_schedules ? (int) $active['enabled'] : 1; $edit_name = $has_schedules ? (string) $active['name'] : ''; $edit_id = $has_schedules ? (string) $active['id'] : ''; $mocks_enabled = class_exists( 'UXPack_Pro_Mocks', false ) && UXPack_Pro_Mocks::is_enabled(); ?>
    render_page_header( __( 'Scheduled Backups', 'uxpack-basic' ) ); ?>

    0 ) : ?>
    0 && ( '' !== $last_status || ! empty( $schedule['last_message'] ) ) ) : ?>

    ' . esc_html( UXPack_Schedule::get_current_time_label() ) . '', esc_html( wp_timezone_string() ), esc_html( UXPack_Schedule::get_trigger_mode_label() ) ); ?>

    render_page_footer(); ?>
    get_installer_cleanup_files(); if ( empty( $cleanup_files ) ) { return; } $tools_url = admin_url( 'admin.php?page=uxpack-tools#cleanup-installer-files' ); $message = sprintf( /* translators: 1: number of files, 2: opening anchor tag, 3: closing anchor tag */ esc_html__( 'UXPack installer files are still present in your WordPress root directory (%1$d file(s)). Remove them as soon as possible for security. %2$sOpen cleanup tools%3$s.', 'uxpack-basic' ), count( $cleanup_files ), '', '' ); $this->render_admin_notice( $message, 'error', false ); } /** * Render tools page. */ public function render_tools_page() { if ( ! UXPack_Capabilities::current_user_can( 'use_tools' ) ) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- flash notice after capability check. $deleted = isset( $_GET['uxpack_deleted'] ) ? absint( wp_unslash( $_GET['uxpack_deleted'] ) ) : 0; $cleanup_files = $this->get_installer_cleanup_files(); ?>
    0 ) : ?> render_admin_notice( sprintf( /* translators: %d: number of files deleted */ esc_html__( 'Deleted %d file(s).', 'uxpack-basic' ), $deleted ), 'success', true, true ); ?> render_page_header( __( 'Tools', 'uxpack-basic' ) ); ?>

    render_page_footer(); ?>
    render_admin_notice( esc_html__( 'Settings reset to default values.', 'uxpack-basic' ), 'success', true, true ); } if ( isset( $_GET['uxpack_storage_deleted'] ) && '1' === sanitize_text_field( wp_unslash( $_GET['uxpack_storage_deleted'] ) ) ) { $this->render_admin_notice( esc_html__( 'Backup storage directory deleted.', 'uxpack-basic' ), 'success', true, true ); } if ( ! empty( $_GET['uxpack_settings_reset_error'] ) ) { $reset_error = sanitize_key( wp_unslash( $_GET['uxpack_settings_reset_error'] ) ); $reset_error_messages = array( 'none_selected' => __( 'Please select at least one reset option.', 'uxpack-basic' ), 'storage' => __( 'The backup storage directory could not be deleted.', 'uxpack-basic' ), ); if ( isset( $reset_error_messages[ $reset_error ] ) ) { $this->render_admin_notice( $reset_error_messages[ $reset_error ], 'error', true, true ); } } if ( isset( $_GET['uxpack_settings_imported'] ) && '1' === sanitize_text_field( wp_unslash( $_GET['uxpack_settings_imported'] ) ) ) { $import_count = isset( $_GET['uxpack_settings_import_count'] ) ? max( 0, absint( wp_unslash( $_GET['uxpack_settings_import_count'] ) ) ) : 0; $import_message = $import_count > 0 ? sprintf( /* translators: %d: number of imported settings */ _n( '%d setting imported.', '%d settings imported.', $import_count, 'uxpack-basic' ), $import_count ) : esc_html__( 'Settings imported.', 'uxpack-basic' ); $this->render_admin_notice( $import_message, 'success', true, true ); } if ( ! empty( $_GET['uxpack_settings_import_error'] ) ) { $import_error = sanitize_key( wp_unslash( $_GET['uxpack_settings_import_error'] ) ); $import_error_messages = array( 'upload' => __( 'The settings file could not be uploaded.', 'uxpack-basic' ), 'invalid' => __( 'The settings file is not valid.', 'uxpack-basic' ), 'empty' => __( 'No recognized settings were found in the file.', 'uxpack-basic' ), 'denied' => __( 'Permission denied.', 'uxpack-basic' ), ); $import_error_message = isset( $import_error_messages[ $import_error ] ) ? $import_error_messages[ $import_error ] : esc_html__( 'Settings could not be imported.', 'uxpack-basic' ); $this->render_admin_notice( $import_error_message, 'error', true, true ); } // phpcs:enable WordPress.Security.NonceVerification.Recommended } /** * Render settings page. */ public function render_settings_page() { if ( ! UXPack_Capabilities::current_user_can( 'manage_settings' ) ) { return; } $is_directory_edition = UXPack_License::is_directory_edition(); $storage = get_option( 'uxpack_storage_path', '' ); $max_backups = (int) get_option( 'uxpack_max_backups', $is_directory_edition ? 5 : 0 ); $health_warnings_enabled = (int) get_option( 'uxpack_health_warnings_enabled', 1 ); $health_min_disk_mb = (int) get_option( 'uxpack_health_min_disk_mb', 500 ); $health_stale_days = (int) get_option( 'uxpack_health_stale_days', 7 ); $enable_log = (int) get_option( 'uxpack_enable_log', 1 ); $activity_log_per_page = (int) get_option( 'uxpack_activity_log_per_page', 25 ); $email_after = (int) get_option( 'uxpack_email_after_backup', 0 ); $email_failure = (int) get_option( 'uxpack_email_on_backup_failure', 0 ); $email_restore_success = (int) get_option( 'uxpack_email_on_restore_success', 0 ); $email_restore_failure = (int) get_option( 'uxpack_email_on_restore_failure', 0 ); $restore_verify_before = (int) get_option( 'uxpack_restore_verify_before', 0 ); $auto_verify_after_backup = (int) get_option( 'uxpack_auto_verify_after_backup', 0 ); $email_recipient = get_option( 'uxpack_email_after_backup_recipient', '' ); $compression = get_option( 'uxpack_backup_compression', 'store' ); $exclude_paths = get_option( 'uxpack_exclude_paths', '' ); $exclude_paths_selected = self::parse_exclude_paths_option( $exclude_paths ); if ( empty( $storage ) ) { $storage = UXPack_Backup::get_default_storage_path(); } $is_directory_edition = UXPack_License::is_directory_edition(); $license_activation_usage = UXPack_License::get_activation_usage_label(); $show_license_status = UXPack_License::should_display_status_label(); $show_license_usage = UXPack_License::should_display_activation_usage() && '' !== $license_activation_usage; $license_tier_label = UXPack_License::get_tier_badge_label(); $license_status_label = UXPack_License::get_status_label(); $license_status_message = UXPack_License::get_status_message_for_display(); $is_pro_license = UXPack_License::is_pro(); $settings_tab_locks = self::get_settings_pro_only_tabs(); $settings_tab_class = static function ( $tab_id, $extra = '' ) use ( $settings_tab_locks ) { $classes = 'uxpack-settings-tabs__tab'; if ( ! empty( $settings_tab_locks[ $tab_id ] ) ) { $classes .= ' is-pro-locked'; } $extra = trim( (string) $extra ); if ( '' !== $extra ) { $classes .= ' ' . $extra; } return $classes; }; ?>
    render_page_header( __( 'UXPack Settings', 'uxpack-basic' ) ); ?> render_settings_page_flash_notices(); ?>
    render_settings_license_fields(); } ?>
    render_settings_updates_panel(); } ?> render_settings_optimize_panel(); } ?> render_settings_encryption_panel(); } ?>
    render_page_footer(); ?>
    $status, 'started' => current_time( 'timestamp' ), 'type' => '', 'message' => '', 'filename' => '', 'finished' => 0, ); if ( is_array( $data ) ) { $state = array_merge( $state, $data ); } $state['status'] = $status; if ( 'running' === $status ) { $now = current_time( 'timestamp' ); $state['started'] = $now; $state['updated'] = $now; $state['finished'] = 0; $state['cancel_requested'] = 0; // Keep caller-provided phase (e.g. chunked db/files); default empty only when omitted. if ( ! is_array( $data ) || ! array_key_exists( 'phase', $data ) ) { $state['phase'] = ''; } } else { $state['finished'] = current_time( 'timestamp' ); $state['updated'] = $state['finished']; } self::clear_backup_cancel_flag(); update_option( 'uxpack_backup_state', $state, false ); } /** * Dedicated cancel flag (not overwritten by heartbeat touches during encryption). */ private static function clear_backup_cancel_flag() { delete_option( 'uxpack_backup_cancel_flag' ); } /** * Read backup state bypassing the in-request options cache. * * Long-running backup requests must see cancel flags set by separate AJAX calls. * * @return array */ private static function get_backup_state_option_fresh() { wp_cache_delete( 'alloptions', 'options' ); wp_cache_delete( 'uxpack_backup_state', 'options' ); $state = get_option( 'uxpack_backup_state', array() ); return is_array( $state ) ? $state : array(); } /** * Bump last-activity time while a backup is running (keeps polling from timing out). */ public static function touch_backup_running_state() { $state = self::get_backup_state_option_fresh(); if ( empty( $state['status'] ) || 'running' !== $state['status'] ) { return; } $state['updated'] = current_time( 'timestamp' ); if ( (int) get_option( 'uxpack_backup_cancel_flag', 0 ) === 1 || ! empty( $state['cancel_requested'] ) ) { $state['cancel_requested'] = 1; $state['phase'] = 'cancelling'; } update_option( 'uxpack_backup_state', $state, false ); } /** * Mark the current backup phase (e.g. finalizing) for extended stall timeouts. * * @param string $phase Phase key. */ public static function set_backup_running_phase( $phase ) { self::patch_backup_running_state( array( 'phase' => sanitize_key( (string) $phase ), ) ); } /** * Merge fields into the current running backup state without resetting started. * * @param array $data Fields to merge. * @return void */ public static function patch_backup_running_state( $data ) { $state = self::get_backup_state_option_fresh(); if ( empty( $state['status'] ) || 'running' !== $state['status'] ) { return; } if ( ! is_array( $data ) ) { $data = array(); } if ( (int) get_option( 'uxpack_backup_cancel_flag', 0 ) === 1 || ! empty( $state['cancel_requested'] ) ) { $state['cancel_requested'] = 1; $state['phase'] = 'cancelling'; } else { $state = array_merge( $state, $data ); $state['status'] = 'running'; } $state['updated'] = current_time( 'timestamp' ); update_option( 'uxpack_backup_state', $state, false ); } /** * Stall timeout before a running backup is treated as failed. * * @param array $state Backup state. * @return int Seconds. */ private static function get_backup_stall_timeout_sec( $state = array() ) { if ( is_array( $state ) && self::state_has_cancel_requested( $state ) ) { $cancel_stall = (int) apply_filters( 'uxpack_backup_cancel_stall_timeout_sec', 120, $state ); return max( 30, $cancel_stall ); } $stall_sec = (int) apply_filters( 'uxpack_backup_stall_timeout_sec', 900 ); if ( $stall_sec < 120 ) { $stall_sec = 120; } if ( is_array( $state ) && ! empty( $state['phase'] ) && in_array( $state['phase'], array( 'finalizing', 'encrypting' ), true ) ) { $stall_sec = (int) apply_filters( 'uxpack_backup_finalize_stall_timeout_sec', max( $stall_sec, 7200 ), $state ); } if ( 'deflate' === get_option( 'uxpack_backup_compression', 'store' ) ) { $stall_sec = (int) apply_filters( 'uxpack_backup_compressed_stall_timeout_sec', max( $stall_sec, 7200 ), $state ); } return max( 120, $stall_sec ); } /** * Throttled touch for heartbeat callbacks during long backup steps. * * @param int $last_touch Unix timestamp of the last touch (by reference). * @param int $interval Minimum seconds between touches. */ public static function maybe_touch_backup_running_state( &$last_touch, $interval = 15 ) { $now = time(); if ( $now - (int) $last_touch >= max( 5, (int) $interval ) ) { self::touch_backup_running_state(); $last_touch = $now; } } /** * Whether the persisted backup state has a pending cancel flag. * * @param array $state Backup state array. * @return bool */ private static function state_has_cancel_requested( $state ) { if ( (int) get_option( 'uxpack_backup_cancel_flag', 0 ) === 1 ) { return true; } return is_array( $state ) && ! empty( $state['cancel_requested'] ); } /** * Remove partial archives from an interrupted backup run. * * @param array $state Running backup state. */ private static function cleanup_running_backup_artifacts( $state ) { if ( ! is_array( $state ) || empty( $state['started'] ) ) { return; } $started = (int) $state['started']; self::clear_chunk_password_transient( $started ); if ( ! empty( $state['filepath'] ) && is_string( $state['filepath'] ) ) { UXPack_Backup::delete_chunk_file_list_sidecar( $state['filepath'] ); if ( is_file( $state['filepath'] ) ) { wp_delete_file( $state['filepath'] ); } $encrypting = $state['filepath'] . '.uxpack-encrypting'; if ( is_file( $encrypting ) ) { wp_delete_file( $encrypting ); } } $storage = UXPack_Backup::get_storage_path(); if ( ! is_dir( $storage ) ) { return; } $patterns = array( $storage . '/uxpack-*.zip', $storage . '/uxpack-*.zip.uxpack-encrypting', $storage . '/uxpack-*.zip.uxpack-filelist', $storage . '/uxpack-*.zip.uxpack-fileindex-tmp', $storage . '/uxpack-db-*.zip', $storage . '/uxpack-db-*.zip.uxpack-encrypting', $storage . '/uxpack-db-*.zip.uxpack-filelist', $storage . '/uxpack-db-*.zip.uxpack-fileindex-tmp', $storage . '/uxpack-inc-*.zip', $storage . '/uxpack-inc-*.zip.uxpack-encrypting', ); foreach ( $patterns as $pattern ) { $files = glob( $pattern ); if ( ! is_array( $files ) ) { continue; } foreach ( $files as $path ) { if ( ! is_file( $path ) ) { continue; } $mtime = filemtime( $path ); if ( false !== $mtime && $mtime >= ( $started - 120 ) ) { wp_delete_file( $path ); } } } } /** * @param int $started Backup started timestamp. * @param string $password Password to store (empty clears). * @return void */ private static function store_chunk_password_transient( $started, $password ) { $key = UXPack_Backup::get_chunk_password_transient_key( $started ); if ( '' === (string) $password ) { delete_transient( $key ); return; } $sealed = self::seal_chunk_password( (string) $password ); if ( '' === $sealed ) { delete_transient( $key ); return; } set_transient( $key, $sealed, 12 * HOUR_IN_SECONDS ); } /** * @param int $started Backup started timestamp. * @return string */ private static function get_chunk_password_transient( $started ) { $val = get_transient( UXPack_Backup::get_chunk_password_transient_key( $started ) ); if ( ! is_string( $val ) || '' === $val ) { return ''; } return self::unseal_chunk_password( $val ); } /** * Seal a chunked-backup password for transient storage (never plaintext). * * @param string $password Plain password. * @return string Sealed payload or empty on failure. */ private static function seal_chunk_password( $password ) { return self::evaluate_seal_chunk_password( (string) $password, (string) wp_salt( 'auth' ) ); } /** * Unseal a chunked-backup password from transient storage. * * @param string $sealed Sealed payload. * @return string Plain password or empty. */ private static function unseal_chunk_password( $sealed ) { return self::evaluate_unseal_chunk_password( (string) $sealed, (string) wp_salt( 'auth' ) ); } /** * Pure seal helper for chunk password transients (AES-256-CBC + site auth salt). * * Never returns plaintext: empty string on failure so callers delete the transient. * * @param string $password Plain password. * @param string $auth_salt Value from wp_salt( 'auth' ). * @return string Sealed payload (`uxpw1:…`) or empty. */ public static function evaluate_seal_chunk_password( $password, $auth_salt ) { $password = (string) $password; $auth_salt = (string) $auth_salt; if ( '' === $password || '' === $auth_salt || ! function_exists( 'openssl_encrypt' ) || ! function_exists( 'random_bytes' ) ) { return ''; } try { $iv = random_bytes( 16 ); } catch ( Exception $e ) { return ''; } $key = hash( 'sha256', 'uxpack-chunk-pw|' . $auth_salt, true ); $enc = openssl_encrypt( $password, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv ); if ( false === $enc ) { return ''; } return 'uxpw1:' . base64_encode( $iv . $enc ); } /** * Pure unseal helper for chunk password transients. * * Rejects legacy plaintext (anything without the `uxpw1:` prefix). * * @param string $sealed Stored transient value. * @param string $auth_salt Value from wp_salt( 'auth' ). * @return string Plain password or empty. */ public static function evaluate_unseal_chunk_password( $sealed, $auth_salt ) { $sealed = (string) $sealed; $auth_salt = (string) $auth_salt; if ( '' === $auth_salt || 0 !== strpos( $sealed, 'uxpw1:' ) || ! function_exists( 'openssl_decrypt' ) ) { return ''; } $raw = base64_decode( substr( $sealed, 6 ), true ); if ( ! is_string( $raw ) || strlen( $raw ) < 17 ) { return ''; } $key = hash( 'sha256', 'uxpack-chunk-pw|' . $auth_salt, true ); $iv = substr( $raw, 0, 16 ); $enc = substr( $raw, 16 ); $out = openssl_decrypt( $enc, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv ); return is_string( $out ) ? $out : ''; } /** * @param int $started Backup started timestamp. * @return void */ private static function clear_chunk_password_transient( $started ) { delete_transient( UXPack_Backup::get_chunk_password_transient_key( $started ) ); } /** * Remove leftover encryption temp files from interrupted backup runs. */ private static function cleanup_orphaned_backup_encrypt_temp_files() { $storage = UXPack_Backup::get_storage_path(); if ( ! is_dir( $storage ) ) { return; } $patterns = array( $storage . '/*.uxpack-encrypting', $storage . '/*.zip.uxpack-encrypting', ); foreach ( $patterns as $pattern ) { $files = glob( $pattern ); if ( ! is_array( $files ) ) { continue; } foreach ( $files as $path ) { if ( is_file( $path ) ) { wp_delete_file( $path ); } } } } /** * Ensure a failed backup does not leave the UI stuck in "running". * * @param array $result execute_backup() return value. */ private static function ensure_backup_terminal_state( $result ) { if ( ! is_array( $result ) || ! empty( $result['success'] ) || ! empty( $result['skipped'] ) ) { return; } $state = self::get_backup_state_option_fresh(); if ( ! is_array( $state ) || empty( $state['status'] ) || 'running' !== $state['status'] ) { return; } $message = isset( $result['message'] ) ? trim( (string) $result['message'] ) : ''; if ( '' === $message ) { $message = __( 'Backup failed.', 'uxpack-basic' ); } $message = UXPack_Backup::normalize_backup_error_message( $message ); self::cleanup_running_backup_artifacts( $state ); self::set_backup_state( 'error', array( 'message' => $message, 'type' => isset( $state['type'] ) ? (string) $state['type'] : '', 'started' => isset( $state['started'] ) ? (int) $state['started'] : 0, 'source' => isset( $state['source'] ) ? (string) $state['source'] : 'manual', 'notification' => 'pending', ) ); self::add_backup_log_entry( $message, 'error' ); } /** * Clear a stuck running backup after the server process is gone. * * @param string $message Optional status message. * @return array Backup state for polling. */ public static function force_clear_running_backup_state( $message = '' ) { $state = self::get_backup_state_option_fresh(); if ( ! is_array( $state ) || empty( $state['status'] ) || 'running' !== $state['status'] ) { self::clear_backup_cancel_flag(); return array( 'status' => 'idle' ); } $recovered = self::recover_backup_state_if_complete( $state ); if ( $recovered ) { self::clear_backup_cancel_flag(); return $recovered; } self::cleanup_running_backup_artifacts( $state ); if ( '' === trim( (string) $message ) ) { $message = self::state_has_cancel_requested( $state ) ? __( 'Backup cancelled.', 'uxpack-basic' ) : __( 'Backup stopped (process no longer running).', 'uxpack-basic' ); } self::add_backup_log_entry( $message, 'step' ); self::set_backup_state( 'cancelled', array( 'message' => $message, 'type' => isset( $state['type'] ) ? (string) $state['type'] : 'full', 'source' => isset( $state['source'] ) ? (string) $state['source'] : 'manual', 'started' => isset( $state['started'] ) ? (int) $state['started'] : current_time( 'timestamp' ), 'notification' => 'sent', ) ); return self::get_backup_state(); } /** * Whether a cooperative cancel was requested for the current manual backup. * * @return bool */ public static function is_backup_cancel_requested() { wp_cache_delete( 'alloptions', 'options' ); wp_cache_delete( 'uxpack_backup_cancel_flag', 'options' ); if ( (int) get_option( 'uxpack_backup_cancel_flag', 0 ) === 1 ) { return true; } $state = self::get_backup_state_option_fresh(); if ( empty( $state['status'] ) || 'running' !== $state['status'] ) { return false; } return ! empty( $state['cancel_requested'] ); } /** * Request cooperative cancel for the current manual backup (Pro). * * @return bool True when the flag was set. */ public static function request_backup_cancel() { if ( ! UXPack_License::can( UXPack_License::FEATURE_BACKUP_CANCEL ) ) { return false; } $state = self::get_backup_state_option_fresh(); if ( empty( $state['status'] ) || 'running' !== $state['status'] ) { return false; } if ( 'manual' !== ( isset( $state['source'] ) ? (string) $state['source'] : '' ) ) { return false; } $state['cancel_requested'] = 1; $state['phase'] = 'cancelling'; $state['updated'] = current_time( 'timestamp' ); update_option( 'uxpack_backup_state', $state, false ); update_option( 'uxpack_backup_cancel_flag', 1, false ); return true; } /** * Finalize a cooperatively cancelled backup run. * * @param array $email_context Email notification context. * @param string $type Backup type. * @param string $message Optional message. * @return array{success: false, cancelled: true, message: string} */ private static function finalize_backup_cancelled( $email_context, $type, $message = '' ) { if ( '' === trim( (string) $message ) ) { $message = __( 'Backup cancelled.', 'uxpack-basic' ); } self::add_backup_log_entry( $message, 'step' ); self::set_backup_state( 'cancelled', array( 'message' => $message, 'type' => $type, 'source' => isset( $email_context['source'] ) ? (string) $email_context['source'] : 'manual', 'started' => isset( $email_context['started'] ) ? (int) $email_context['started'] : current_time( 'timestamp' ), 'notification' => 'sent', 'cancel_requested' => 0, ) ); return array( 'success' => false, 'cancelled' => true, 'message' => $message, ); } /** * If a backup file was created during the current run, mark state as success. * * @param array $state Running backup state. * @return array|null Recovered success state or null. */ public static function recover_backup_state_if_complete( $state ) { if ( ! is_array( $state ) || empty( $state['started'] ) ) { return null; } // Chunked runs leave a partial zip on disk until the final continue — never treat as success. if ( ! empty( $state['mode'] ) && 'chunked' === $state['mode'] ) { $phase = UXPack_Backup::normalize_chunk_phase( isset( $state['phase'] ) ? $state['phase'] : '' ); if ( 'done' !== $phase ) { return null; } } $started = (int) $state['started']; $type = isset( $state['type'] ) ? $state['type'] : 'full'; $prefix = ( 'db' === $type ) ? 'uxpack-db-' : 'uxpack-'; $storage = UXPack_Backup::get_storage_path(); if ( ! is_dir( $storage ) ) { return null; } $files = glob( $storage . '/' . $prefix . '*.zip' ); if ( ! $files ) { return null; } $best_file = null; $best_mtime = 0; foreach ( $files as $path ) { if ( ! is_file( $path ) ) { continue; } $mtime = filemtime( $path ); // File from this run (allow small clock skew before started). if ( $mtime >= ( $started - 120 ) && $mtime >= $best_mtime ) { $best_mtime = $mtime; $best_file = basename( $path ); } } if ( ! $best_file ) { return null; } $success_message = __( 'Backup completed successfully.', 'uxpack-basic' ); $recovered = array( 'status' => 'success', 'message' => $success_message, 'filename' => $best_file, 'type' => $type, 'started' => $started, 'finished' => $best_mtime, 'updated' => current_time( 'timestamp' ), 'source' => isset( $state['source'] ) ? (string) $state['source'] : 'manual', 'source_context' => isset( $state['source_context'] ) ? (string) $state['source_context'] : '', 'notification' => 'pending', ); self::set_backup_state( 'success', $recovered ); $backup_entry = null; foreach ( UXPack_Backup::get_backups() as $backup ) { if ( $backup['filename'] === $best_file ) { $backup_entry = $backup; break; } } self::send_backup_notification( array( 'status' => 'success', 'type' => $type, 'message' => $success_message, 'filename' => $best_file, 'source' => isset( $state['source'] ) ? (string) $state['source'] : 'manual', 'source_context' => isset( $state['source_context'] ) ? (string) $state['source_context'] : '', 'started' => $started, 'backup' => $backup_entry, ) ); return $recovered; } /** * Resolve a stale "running" state (no activity for a long time). */ public static function resolve_stale_backup_state() { $state = get_option( 'uxpack_backup_state', array() ); if ( ! is_array( $state ) || empty( $state['status'] ) || 'running' !== $state['status'] ) { return; } $updated = isset( $state['updated'] ) ? (int) $state['updated'] : (int) ( $state['started'] ?? 0 ); $stall_sec = self::get_backup_stall_timeout_sec( $state ); if ( $updated <= 0 || ( current_time( 'timestamp' ) - $updated ) <= $stall_sec ) { return; } if ( self::recover_backup_state_if_complete( $state ) ) { return; } if ( self::state_has_cancel_requested( $state ) ) { self::force_clear_running_backup_state(); return; } $error_message = __( 'Backup timed out or was interrupted.', 'uxpack-basic' ); self::set_backup_state( 'error', array( 'message' => $error_message, 'type' => isset( $state['type'] ) ? $state['type'] : '', 'started' => isset( $state['started'] ) ? (int) $state['started'] : 0, 'source' => isset( $state['source'] ) ? (string) $state['source'] : 'manual', 'notification' => 'pending', ) ); self::send_backup_notification( array( 'status' => 'failure', 'type' => isset( $state['type'] ) ? (string) $state['type'] : 'full', 'message' => $error_message, 'source' => isset( $state['source'] ) ? (string) $state['source'] : 'manual', 'source_context' => isset( $state['source_context'] ) ? (string) $state['source_context'] : '', 'started' => isset( $state['started'] ) ? (int) $state['started'] : 0, ) ); } /** * Read backup progress for status polling. * * @return array */ public static function get_backup_state() { self::resolve_stale_backup_state(); $state = get_option( 'uxpack_backup_state', array() ); if ( ! is_array( $state ) || empty( $state['status'] ) ) { return array( 'status' => 'idle' ); } if ( 'running' === $state['status'] ) { $updated = isset( $state['updated'] ) ? (int) $state['updated'] : (int) ( $state['started'] ?? 0 ); $stall_sec = self::get_backup_stall_timeout_sec( $state ); if ( $updated > 0 && ( current_time( 'timestamp' ) - $updated ) > $stall_sec ) { $recovered = self::recover_backup_state_if_complete( $state ); if ( $recovered ) { return $recovered; } if ( self::state_has_cancel_requested( $state ) ) { return self::force_clear_running_backup_state(); } $error_state = array( 'status' => 'error', 'message' => __( 'Backup timed out or was interrupted.', 'uxpack-basic' ), 'type' => isset( $state['type'] ) ? $state['type'] : '', ); self::set_backup_state( 'error', $error_state ); return $error_state; } } if ( 'running' === $state['status'] && self::is_backup_cancel_requested() ) { $state['cancel_requested'] = 1; } if ( 'error' === $state['status'] && ! empty( $state['message'] ) ) { $state['message'] = UXPack_Backup::normalize_backup_error_message( (string) $state['message'] ); } return $state; } /** * AJAX: Poll backup status while a long-running backup is in progress. */ public function ajax_backup_status() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'view_backups' ) && ! UXPack_Capabilities::current_user_can( 'run_backups' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } wp_send_json_success( self::get_backup_state() ); } /** * AJAX: Request cooperative cancel for a running manual backup (Pro). */ public function ajax_cancel_backup() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'run_backups' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } if ( ! UXPack_License::can( UXPack_License::FEATURE_BACKUP_CANCEL ) ) { wp_send_json_error( array( 'message' => esc_html( UXPack_License::get_upgrade_message( UXPack_License::FEATURE_BACKUP_CANCEL ) ) ) ); } if ( ! self::request_backup_cancel() ) { wp_send_json_error( array( 'message' => __( 'No running manual backup can be cancelled.', 'uxpack-basic' ) ) ); } wp_send_json_success( array_merge( self::get_backup_state(), array( 'message' => __( 'Cancelling backup...', 'uxpack-basic' ), ) ) ); } /** * AJAX: Force-clear a stuck running backup (e.g. after server restart). */ public function ajax_force_clear_backup() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'run_backups' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } if ( ! UXPack_License::can( UXPack_License::FEATURE_BACKUP_CANCEL ) ) { wp_send_json_error( array( 'message' => esc_html( UXPack_License::get_upgrade_message( UXPack_License::FEATURE_BACKUP_CANCEL ) ) ) ); } wp_send_json_success( self::force_clear_running_backup_state() ); } /** * Run a backup (manual or scheduled). * * @param string $type Backup type: full, db, or delta. * @param array $options Optional. source (manual|schedule|pre_update), context, label, on_log callback. * @return array{success: bool, message: string, filename?: string, skipped?: bool} */ public static function execute_backup( $type, $options = array() ) { $defaults = array( 'source' => 'manual', 'context' => '', 'label' => '', 'password' => '', 'password_confirm' => '', 'destinations' => array( 'local' ), 'on_log' => null, 'on_started' => null, ); $options = wp_parse_args( $options, $defaults ); if ( class_exists( 'UXPack_Remote_Storage', false ) ) { $options['destinations'] = UXPack_Remote_Storage::sanitize_destinations( $options['destinations'] ); $dest_ok = UXPack_Remote_Storage::validate_destinations_for_run( $options['destinations'] ); if ( is_wp_error( $dest_ok ) ) { return array( 'success' => false, 'message' => $dest_ok->get_error_message(), ); } } else { $options['destinations'] = array( 'local' ); } $allowed_types = UXPack_Backup::get_allowed_backup_types(); $type = UXPack_Backup::sanitize_backup_type( $type, 'full' ); $email_context = array( 'type' => in_array( $type, $allowed_types, true ) ? $type : 'full', 'source' => sanitize_key( (string) $options['source'] ), 'source_context' => sanitize_key( (string) $options['context'] ), ); $state = self::get_backup_state(); if ( isset( $state['status'] ) && 'running' === $state['status'] ) { return array( 'success' => false, 'message' => __( 'A backup is already in progress.', 'uxpack-basic' ), 'skipped' => true, ); } if ( class_exists( 'UXPack_Restore', false ) && UXPack_Restore::is_running() ) { return array( 'success' => false, 'message' => __( 'A restore is already in progress.', 'uxpack-basic' ), 'skipped' => true, ); } $type = in_array( $type, $allowed_types, true ) ? $type : 'full'; if ( class_exists( 'UXPack_Delta' ) && UXPack_Delta::is_delta_type( $type ) ) { $delta_allowed = UXPack_Delta::can_run_delta(); if ( is_wp_error( $delta_allowed ) ) { $msg = $delta_allowed->get_error_message(); self::add_backup_log_entry( $msg, 'error' ); self::set_backup_state( 'error', array( 'message' => $msg, 'type' => $type, 'source' => $email_context['source'], 'started' => isset( $email_context['started'] ) ? (int) $email_context['started'] : current_time( 'timestamp' ), 'notification' => 'pending', ) ); return array( 'success' => false, 'message' => $msg, ); } if ( ! UXPack_Delta::has_delta_base_backup() ) { $msg = __( 'Create a full backup before running a delta backup.', 'uxpack-basic' ); self::add_backup_log_entry( $msg, 'error' ); self::set_backup_state( 'error', array( 'message' => $msg, 'type' => $type, 'source' => $email_context['source'], 'started' => current_time( 'timestamp' ), 'notification' => 'pending', ) ); return array( 'success' => false, 'message' => $msg, ); } } if ( 'schedule' === $options['source'] ) { self::add_backup_log_entry( __( 'Scheduled backup started.', 'uxpack-basic' ), 'step' ); } elseif ( 'pre_update' === $options['source'] ) { $context = isset( $options['context'] ) ? sanitize_key( (string) $options['context'] ) : 'update'; self::add_backup_log_entry( sprintf( /* translators: %s: update context, e.g. plugin or core */ __( 'Pre-update backup started (%s).', 'uxpack-basic' ), $context ), 'step' ); } self::cleanup_orphaned_backup_encrypt_temp_files(); if ( class_exists( 'UXPack_Preflight' ) && UXPack_Preflight::should_block_on_failure() ) { $preflight = UXPack_Preflight::run_for_backup(); if ( is_wp_error( $preflight ) ) { $msg = $preflight->get_error_message(); self::add_backup_log_entry( $msg, 'error' ); return array( 'success' => false, 'message' => $msg, ); } } self::set_backup_state( 'running', array( 'type' => $type, 'source' => $options['source'], 'source_context' => sanitize_key( (string) $options['context'] ), 'destinations' => $options['destinations'], 'notification' => 'pending', ) ); if ( is_callable( $options['on_started'] ) ) { call_user_func( $options['on_started'] ); } $running_state = self::get_backup_state(); $email_context['started'] = isset( $running_state['started'] ) ? (int) $running_state['started'] : current_time( 'timestamp' ); $on_log = is_callable( $options['on_log'] ) ? $options['on_log'] : null; $last_touch = 0; $log_callback = function ( $message ) use ( $on_log, &$last_touch ) { if ( self::is_backup_cancel_requested() ) { throw new UXPack_Backup_Cancelled_Exception(); } if ( $message !== null && $message !== '' ) { self::add_backup_log_entry( $message, 'step', '' ); self::touch_backup_running_state(); $last_touch = time(); } elseif ( null === $message ) { self::maybe_touch_backup_running_state( $last_touch ); } if ( $on_log ) { $on_log( $message ); } }; $manifest_meta = self::build_backup_manifest_meta( $options ); $password = UXPack_Backup::resolve_run_backup_password( array( 'source' => $options['source'], 'password' => isset( $options['password'] ) ? (string) $options['password'] : '', 'password_confirm' => isset( $options['password_confirm'] ) ? (string) $options['password_confirm'] : '', ) ); if ( is_wp_error( $password ) ) { $msg = $password->get_error_message(); self::add_backup_log_entry( $msg, 'error' ); self::set_backup_state( 'error', array( 'message' => $msg, 'type' => $type, 'source' => $email_context['source'], 'started' => $email_context['started'], 'notification' => 'pending', ) ); self::send_backup_notification( array_merge( $email_context, array( 'status' => 'failure', 'message' => $msg, 'label' => isset( $manifest_meta['label'] ) ? (string) $manifest_meta['label'] : '', ) ) ); return array( 'success' => false, 'message' => $msg, ); } if ( '' !== $password && class_exists( 'UXPack_Encryption', false ) ) { $manifest_meta['encrypted'] = true; $manifest_meta['encryption_method'] = UXPack_Encryption::get_encryption_method_key(); } if ( class_exists( 'UXPack_Optimize' ) && UXPack_Optimize::should_run() ) { UXPack_Optimize::run( $log_callback ); } try { $result = UXPack_Backup::run_backup( $type, $log_callback, $manifest_meta, $password ); } catch ( UXPack_Backup_Cancelled_Exception $e ) { return self::finalize_backup_cancelled( $email_context, $type ); } catch ( Throwable $e ) { $msg = UXPack_Backup::normalize_backup_error_message( $e->getMessage() ); self::add_backup_log_entry( $msg, 'error' ); self::set_backup_state( 'error', array( 'message' => $msg, 'type' => $type, 'source' => $email_context['source'], 'started' => $email_context['started'], 'notification' => 'pending', ) ); self::send_backup_notification( array_merge( $email_context, array( 'status' => 'failure', 'message' => $msg, 'label' => isset( $manifest_meta['label'] ) ? (string) $manifest_meta['label'] : '', ) ) ); return array( 'success' => false, 'message' => $msg, ); } if ( $result['success'] ) { $success_message = isset( $result['message'] ) ? $result['message'] : __( 'Backup completed successfully.', 'uxpack-basic' ); $success_file = isset( $result['filename'] ) ? $result['filename'] : ''; self::add_backup_log_entry( $success_message, 'success', $success_file ); // Remote handoff before publishing success state (avoids poll race without upload_id). $result = self::attach_destination_uploads( $result, $options ); self::set_backup_state( 'success', array( 'message' => $success_message, 'filename' => $success_file, 'type' => $type, 'source' => $email_context['source'], 'started' => $email_context['started'], 'notification' => 'pending', 'destinations' => isset( $result['destinations'] ) ? $result['destinations'] : $options['destinations'], 'keep_local' => isset( $result['keep_local'] ) ? (bool) $result['keep_local'] : true, 'delete_local_after' => ! empty( $result['delete_local_after'] ), 'remote_uploads' => isset( $result['remote_uploads'] ) ? $result['remote_uploads'] : array(), ) ); UXPack_Backup::trim_old_backups(); $backup_entry = null; if ( $success_file ) { foreach ( UXPack_Backup::get_backups() as $backup ) { if ( $backup['filename'] === $success_file ) { $backup_entry = $backup; break; } } } self::send_backup_notification( array_merge( $email_context, array( 'status' => 'success', 'message' => $success_message, 'filename' => $success_file, 'label' => is_array( $backup_entry ) ? UXPack_Backup::get_backup_label( $backup_entry ) : ( isset( $manifest_meta['label'] ) ? (string) $manifest_meta['label'] : '' ), 'backup' => $backup_entry, ) ) ); if ( $success_file && (int) get_option( 'uxpack_auto_verify_after_backup', 0 ) === 1 ) { self::maybe_auto_verify_backup( $success_file ); } if ( $success_file && 'full' === $type && ! UXPack_License::is_directory_edition() ) { try { UXPack_Backup::create_installer_for_backup( $success_file ); } catch ( Throwable $e ) { // Installer can be created on next backup list refresh. } } return $result; } if ( ! empty( $result['cancelled'] ) ) { return self::finalize_backup_cancelled( $email_context, $type, isset( $result['message'] ) ? (string) $result['message'] : '' ); } $message = isset( $result['message'] ) ? (string) $result['message'] : __( 'Unknown error.', 'uxpack-basic' ); $message = UXPack_Backup::normalize_backup_error_message( $message ); self::add_backup_log_entry( $message, 'error' ); self::set_backup_state( 'error', array( 'message' => $message, 'type' => $type, 'source' => $email_context['source'], 'started' => $email_context['started'], 'notification' => 'pending', ) ); self::send_backup_notification( array_merge( $email_context, array( 'status' => 'failure', 'message' => $message, 'label' => isset( $manifest_meta['label'] ) ? (string) $manifest_meta['label'] : '', ) ) ); return array( 'success' => false, 'message' => $message, ); } /** * After a successful local backup, upload to remote destinations when requested. * * @param array $result execute_backup result. * @param array $options Run options including destinations + source. * @return array */ private static function attach_destination_uploads( $result, $options ) { if ( ! is_array( $result ) || empty( $result['success'] ) ) { return $result; } $filename = isset( $result['filename'] ) ? (string) $result['filename'] : ''; if ( '' === $filename ) { return $result; } $destinations = isset( $options['destinations'] ) ? $options['destinations'] : array( 'local' ); if ( class_exists( 'UXPack_Remote_Storage', false ) ) { $destinations = UXPack_Remote_Storage::sanitize_destinations( $destinations ); } else { $destinations = array( 'local' ); } $source = isset( $options['source'] ) ? sanitize_key( (string) $options['source'] ) : 'manual'; $context = array( 'destinations' => $destinations, 'source' => $source, 'upload_mode' => ( 'manual' === $source ) ? 'async_start' : 'sync', ); /** * Fires after a backup archive was written successfully. * * @param string $filename Backup basename. * @param array $context Destinations and source. */ do_action( 'uxpack_backup_completed', $filename, $context ); $remote = array( 'uploads' => array(), 'keep_local' => true, 'errors' => array(), 'delete_local_after' => false, ); if ( class_exists( 'UXPack_Remote_Storage', false ) ) { $remote = UXPack_Remote_Storage::maybe_upload_after_backup( $filename, $context ); } $result['destinations'] = $destinations; $result['keep_local'] = ! empty( $remote['keep_local'] ); $result['delete_local_after'] = ! empty( $remote['delete_local_after'] ); $result['remote_uploads'] = isset( $remote['uploads'] ) && is_array( $remote['uploads'] ) ? $remote['uploads'] : array(); $result['remote_upload_errors'] = isset( $remote['errors'] ) && is_array( $remote['errors'] ) ? $remote['errors'] : array(); return $result; } /** * Build manifest metadata for a backup run. * * @param array $options execute_backup options. * @return array */ private static function build_backup_manifest_meta( $options ) { $source = sanitize_key( (string) $options['source'] ); $context = sanitize_key( (string) $options['context'] ); $label = UXPack_Backup::sanitize_backup_label( $options['label'] ); if ( '' === $label && 'pre_update' === $source ) { $label = UXPack_Backup::format_pre_update_context_label( $context ); } elseif ( '' === $label && 'schedule' === $source ) { $label = __( 'Scheduled backup', 'uxpack-basic' ); } elseif ( '' === $label && 'cli' === $source ) { $label = __( 'WP-CLI backup', 'uxpack-basic' ); } return array( 'label' => $label, 'source' => $source, 'source_context' => $context, ); } /** * Resolve the configured backup notification recipient. * * @return string Empty when no valid recipient is available. */ public static function get_backup_email_recipient() { $to = get_option( 'uxpack_email_after_backup_recipient', '' ); if ( '' === $to || ! is_email( $to ) ) { $to = get_option( 'admin_email' ); } if ( ! is_email( $to ) ) { return ''; } return $to; } /** * Build a dedupe key for a backup notification. * * @param array $context Notification context. * @return string */ private static function get_backup_notification_dedupe_key( $context ) { $status = isset( $context['status'] ) ? sanitize_key( (string) $context['status'] ) : ''; $filename = isset( $context['filename'] ) ? sanitize_file_name( (string) $context['filename'] ) : ''; $started = isset( $context['started'] ) ? (int) $context['started'] : 0; return 'uxpack_notify_' . md5( $status . '|' . $filename . '|' . $started ); } /** * Mark a backup notification as sent in backup state. */ private static function mark_backup_notification_sent_in_state() { $state = get_option( 'uxpack_backup_state', array() ); if ( ! is_array( $state ) ) { return; } $state['notification'] = 'sent'; update_option( 'uxpack_backup_state', $state, false ); } /** * Retry pending backup notifications (e.g. after a request was interrupted). */ public function maybe_send_pending_backup_notifications() { $state = get_option( 'uxpack_backup_state', array() ); if ( ! is_array( $state ) || empty( $state['status'] ) ) { return; } if ( empty( $state['notification'] ) || 'pending' !== $state['notification'] ) { return; } if ( ! in_array( $state['status'], array( 'success', 'error' ), true ) ) { return; } $status = ( 'success' === $state['status'] ) ? 'success' : 'failure'; if ( 'success' === $status && (int) get_option( 'uxpack_email_after_backup', 0 ) !== 1 ) { self::mark_backup_notification_sent_in_state(); return; } if ( 'failure' === $status && (int) get_option( 'uxpack_email_on_backup_failure', 0 ) !== 1 ) { self::mark_backup_notification_sent_in_state(); return; } $backup_entry = null; if ( ! empty( $state['filename'] ) ) { foreach ( UXPack_Backup::get_backups() as $backup ) { if ( $backup['filename'] === $state['filename'] ) { $backup_entry = $backup; break; } } } self::send_backup_notification( array( 'status' => $status, 'type' => isset( $state['type'] ) ? (string) $state['type'] : 'full', 'message' => isset( $state['message'] ) ? (string) $state['message'] : '', 'filename' => isset( $state['filename'] ) ? (string) $state['filename'] : '', 'source' => isset( $state['source'] ) ? (string) $state['source'] : 'manual', 'source_context' => isset( $state['source_context'] ) ? (string) $state['source_context'] : '', 'started' => isset( $state['started'] ) ? (int) $state['started'] : 0, 'backup' => $backup_entry, ) ); } /** * Build email headers for UXPack notifications. * * @return string[] */ private static function get_backup_email_headers() { return array( 'Content-Type: text/plain; charset=UTF-8' ); } /** * Resolve the From address used for UXPack emails. * * @return string */ private static function get_backup_email_from_address() { $from_email = apply_filters( 'uxpack_backup_email_from_address', get_option( 'admin_email' ) ); return is_email( $from_email ) ? $from_email : get_option( 'admin_email' ); } /** * Resolve the From name used for UXPack emails. * * @return string */ private static function get_backup_email_from_name() { return apply_filters( 'uxpack_backup_email_from_name', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ); } /** * Send mail with a site-specific From header. * * @param string $to Recipient. * @param string $subject Subject. * @param string $body Body. * @param string[] $headers Headers. * @return bool */ private static function deliver_backup_email( $to, $subject, $body, $headers = array() ) { $from_email = self::get_backup_email_from_address(); $from_name = self::get_backup_email_from_name(); $from_filter = static function () use ( $from_email ) { return $from_email; }; $name_filter = static function () use ( $from_name ) { return $from_name; }; add_filter( 'wp_mail_from', $from_filter ); add_filter( 'wp_mail_from_name', $name_filter ); $sent = wp_mail( $to, $subject, $body, $headers ); remove_filter( 'wp_mail_from', $from_filter ); remove_filter( 'wp_mail_from_name', $name_filter ); if ( ! $sent ) { global $phpmailer; $error = ''; if ( isset( $phpmailer ) && is_object( $phpmailer ) && ! empty( $phpmailer->ErrorInfo ) ) { $error = (string) $phpmailer->ErrorInfo; } update_option( 'uxpack_last_email_error', array( 'time' => current_time( 'timestamp' ), 'to' => $to, 'subject' => $subject, 'error' => $error, ), false ); self::add_backup_log_entry( $error ? sprintf( /* translators: 1: recipient email, 2: mailer error */ __( 'Backup notification email could not be sent to %1$s: %2$s', 'uxpack-basic' ), $to, $error ) : sprintf( /* translators: %s: recipient email */ __( 'Backup notification email could not be sent to %s.', 'uxpack-basic' ), $to ), 'error' ); return false; } delete_option( 'uxpack_last_email_error' ); return true; } /** * Build the plain-text body for a backup notification. * * @param array $context Notification context. * @return array{subject: string, body: string}|null */ private static function build_backup_notification_message( $context ) { $status = isset( $context['status'] ) ? sanitize_key( (string) $context['status'] ) : ''; if ( ! in_array( $status, array( 'success', 'failure' ), true ) ) { return null; } $site_name = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); $context_type = isset( $context['type'] ) ? sanitize_key( (string) $context['type'] ) : 'full'; $type = UXPack_Backup::format_backup_type_label( array( 'filename' => '', 'manifest' => array( 'backup_type' => $context_type ), ) ); $message = isset( $context['message'] ) ? (string) $context['message'] : ''; $filename = isset( $context['filename'] ) ? (string) $context['filename'] : ''; $label = isset( $context['label'] ) ? (string) $context['label'] : ''; $source = isset( $context['source'] ) ? sanitize_key( (string) $context['source'] ) : 'manual'; $source_context = isset( $context['source_context'] ) ? sanitize_key( (string) $context['source_context'] ) : ''; $backups_url = admin_url( 'admin.php?page=uxpack' ); $log_url = admin_url( 'admin.php?page=uxpack-log' ); if ( 'success' === $status ) { $subject = sprintf( /* translators: %s: site name */ __( '[%s] UXPack backup completed', 'uxpack-basic' ), $site_name ); } else { $subject = sprintf( /* translators: %s: site name */ __( '[%s] UXPack backup failed', 'uxpack-basic' ), $site_name ); } $lines = array(); $lines[] = 'success' === $status ? __( 'Backup completed successfully.', 'uxpack-basic' ) : __( 'Backup failed.', 'uxpack-basic' ); $lines[] = ''; $lines[] = sprintf( /* translators: %s: backup type label */ __( 'Type: %s', 'uxpack-basic' ), $type ); $lines[] = sprintf( /* translators: %s: backup source label */ __( 'Source: %s', 'uxpack-basic' ), UXPack_Backup::format_backup_source_label( $source, $source_context ) ); if ( '' !== $label ) { $lines[] = sprintf( /* translators: %s: backup label */ __( 'Label: %s', 'uxpack-basic' ), $label ); } if ( '' !== $filename ) { $lines[] = sprintf( /* translators: %s: backup filename */ __( 'File: %s', 'uxpack-basic' ), $filename ); } $backup = isset( $context['backup'] ) && is_array( $context['backup'] ) ? $context['backup'] : null; if ( $backup && ! empty( $backup['manifest']['encrypted'] ) ) { $lines[] = __( 'Encrypted: yes (password required to open the archive)', 'uxpack-basic' ); } if ( '' !== $message ) { $lines[] = sprintf( /* translators: %s: status message */ __( 'Message: %s', 'uxpack-basic' ), $message ); } if ( $backup ) { $site_info = UXPack_Backup::format_backup_site_info( $backup ); if ( '' !== $site_info && '—' !== $site_info ) { $lines[] = sprintf( /* translators: %s: WP/PHP/DB summary */ __( 'Site info: %s', 'uxpack-basic' ), $site_info ); } if ( ! empty( $backup['size'] ) ) { $lines[] = sprintf( /* translators: %s: formatted file size */ __( 'Size: %s', 'uxpack-basic' ), UXPack_Backup::format_size( (int) $backup['size'] ) ); } } $lines[] = sprintf( /* translators: %s: site URL */ __( 'Site: %s', 'uxpack-basic' ), home_url( '/' ) ); $lines[] = ''; $lines[] = sprintf( /* translators: %s: admin URL */ __( 'Backups: %s', 'uxpack-basic' ), $backups_url ); $lines[] = sprintf( /* translators: %s: admin URL */ __( 'Activity log: %s', 'uxpack-basic' ), $log_url ); return array( 'subject' => $subject, 'body' => implode( "\n", $lines ), ); } /** * Send a backup success or failure notification email. * * @param array $context Notification context. * @return bool True when the email was sent or intentionally skipped as duplicate/disabled. */ public static function send_backup_notification( $context ) { if ( ! UXPack_License::can( UXPack_License::FEATURE_EMAIL_NOTIFICATIONS ) ) { self::mark_backup_notification_sent_in_state(); return true; } $status = isset( $context['status'] ) ? sanitize_key( (string) $context['status'] ) : ''; if ( 'success' === $status && (int) get_option( 'uxpack_email_after_backup', 0 ) !== 1 ) { self::mark_backup_notification_sent_in_state(); return true; } if ( 'failure' === $status && (int) get_option( 'uxpack_email_on_backup_failure', 0 ) !== 1 ) { self::mark_backup_notification_sent_in_state(); return true; } if ( ! in_array( $status, array( 'success', 'failure' ), true ) ) { return false; } $dedupe_key = self::get_backup_notification_dedupe_key( $context ); if ( get_transient( $dedupe_key ) ) { self::mark_backup_notification_sent_in_state(); return true; } $to = self::get_backup_email_recipient(); if ( '' === $to ) { return false; } $message_data = self::build_backup_notification_message( $context ); if ( null === $message_data ) { return false; } $sent = self::deliver_backup_email( $to, $message_data['subject'], $message_data['body'], self::get_backup_email_headers() ); if ( $sent ) { set_transient( $dedupe_key, 1, WEEK_IN_SECONDS ); self::mark_backup_notification_sent_in_state(); } return $sent; } /** * Send a restore success or failure notification email. * * @param array $context Notification context. * @return bool */ public static function send_restore_notification( $context ) { if ( ! UXPack_License::can( UXPack_License::FEATURE_EMAIL_NOTIFICATIONS ) ) { return true; } $status = isset( $context['status'] ) ? sanitize_key( (string) $context['status'] ) : ''; if ( 'success' === $status && (int) get_option( 'uxpack_email_on_restore_success', 0 ) !== 1 ) { return true; } if ( 'failure' === $status && (int) get_option( 'uxpack_email_on_restore_failure', 0 ) !== 1 ) { return true; } if ( ! in_array( $status, array( 'success', 'failure' ), true ) ) { return false; } $to = self::get_backup_email_recipient(); if ( '' === $to ) { return false; } $site_name = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); $filename = isset( $context['filename'] ) ? (string) $context['filename'] : ''; $message = isset( $context['message'] ) ? (string) $context['message'] : ''; $mode = isset( $context['mode'] ) ? sanitize_key( (string) $context['mode'] ) : 'full'; $mode_label = 'db' === $mode ? __( 'Database only', 'uxpack-basic' ) : ( 'files' === $mode ? __( 'Files only', 'uxpack-basic' ) : __( 'Files and database', 'uxpack-basic' ) ); if ( 'success' === $status ) { $subject = sprintf( /* translators: %s: site name */ __( '[%s] UXPack restore completed', 'uxpack-basic' ), $site_name ); } else { $subject = sprintf( /* translators: %s: site name */ __( '[%s] UXPack restore failed', 'uxpack-basic' ), $site_name ); } $body_lines = array( 'success' === $status ? __( 'A restore completed on your site.', 'uxpack-basic' ) : __( 'A restore failed on your site.', 'uxpack-basic' ), '', sprintf( /* translators: %s: backup filename */ __( 'Backup: %s', 'uxpack-basic' ), $filename ), sprintf( /* translators: %s: restore mode label */ __( 'Mode: %s', 'uxpack-basic' ), $mode_label ), ); if ( '' !== $message ) { $body_lines[] = sprintf( /* translators: %s: status message */ __( 'Message: %s', 'uxpack-basic' ), $message ); } $body_lines[] = ''; $body_lines[] = admin_url( 'admin.php?page=uxpack-log' ); return self::deliver_backup_email( $to, $subject, implode( "\n", $body_lines ), self::get_backup_email_headers() ); } /** * Run automatic verification after a successful backup when enabled. * * @param string $filename Backup filename. * @return void */ private static function maybe_auto_verify_backup( $filename ) { if ( ! class_exists( 'UXPack_Backup_Meta', false ) ) { return; } if ( ! UXPack_License::can( UXPack_License::FEATURE_AUTO_VERIFY ) ) { return; } $storage = UXPack_Backup::get_storage_path(); $zip_path = $storage . '/' . $filename; $password = ''; if ( UXPack_Backup::zip_requires_password( $zip_path ) ) { $password = UXPack_Backup::resolve_verify_password( $zip_path ); if ( '' === $password ) { self::add_backup_log_entry( __( 'Automatic verification skipped — encrypted backup uses a per-backup password that is not available for background checks.', 'uxpack-basic' ), 'step', $filename ); return; } } $result = UXPack_Backup::verify_backup( $filename, $password ); $message = ! empty( $result['message'] ) ? (string) $result['message'] : ''; if ( ! empty( $result['success'] ) ) { self::add_backup_log_entry( $message ? $message : __( 'Automatic verification completed.', 'uxpack-basic' ), 'success', $filename ); return; } self::add_backup_log_entry( $message ? $message : __( 'Automatic verification failed.', 'uxpack-basic' ), 'error', $filename ); } /** * Send a test notification email to verify delivery settings. * * @return array{success: bool, message: string} */ public static function send_test_notification_email() { $to = self::get_backup_email_recipient(); if ( '' === $to ) { return array( 'success' => false, 'message' => __( 'No valid recipient email address is configured.', 'uxpack-basic' ), ); } $site_name = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); $subject = sprintf( /* translators: %s: site name */ __( '[%s] UXPack test email', 'uxpack-basic' ), $site_name ); $lines = array( __( 'This is a test email from UXPack backup notifications.', 'uxpack-basic' ), '', sprintf( /* translators: %s: recipient email */ __( 'Recipient: %s', 'uxpack-basic' ), $to ), sprintf( /* translators: %s: site URL */ __( 'Site: %s', 'uxpack-basic' ), home_url( '/' ) ), '', __( 'If you received this message, WordPress can send UXPack backup notifications to this address.', 'uxpack-basic' ), ); $sent = self::deliver_backup_email( $to, $subject, implode( "\n", $lines ), self::get_backup_email_headers() ); if ( $sent ) { return array( 'success' => true, 'message' => sprintf( /* translators: %s: recipient email */ __( 'Test email sent to %s.', 'uxpack-basic' ), $to ), ); } $last_error = get_option( 'uxpack_last_email_error', array() ); $error_text = is_array( $last_error ) && ! empty( $last_error['error'] ) ? (string) $last_error['error'] : ''; return array( 'success' => false, 'message' => $error_text ? sprintf( /* translators: 1: recipient email, 2: mailer error */ __( 'Test email could not be sent to %1$s: %2$s', 'uxpack-basic' ), $to, $error_text ) : sprintf( /* translators: %s: recipient email */ __( 'Test email could not be sent to %s.', 'uxpack-basic' ), $to ), ); } /** * AJAX: Send a test notification email. */ public function ajax_send_test_email() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'manage_settings' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } if ( ! UXPack_License::can( UXPack_License::FEATURE_EMAIL_NOTIFICATIONS ) ) { UXPack_License::deny_pro_feature_json( UXPack_License::FEATURE_EMAIL_NOTIFICATIONS ); } $result = self::send_test_notification_email(); if ( ! empty( $result['success'] ) ) { wp_send_json_success( array( 'message' => $result['message'] ) ); } wp_send_json_error( array( 'message' => $result['message'] ) ); } /** * @deprecated 0.7.0 Use send_backup_notification(). * @param array $result Backup result with 'filename', 'message'. */ public static function send_backup_success_email( $result ) { self::send_backup_notification( array( 'status' => 'success', 'type' => 'full', 'message' => isset( $result['message'] ) ? $result['message'] : '', 'filename' => isset( $result['filename'] ) ? $result['filename'] : '', ) ); } /** * AJAX: Run backup. */ public function ajax_run_backup() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'run_backups' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } $state = self::get_backup_state(); if ( isset( $state['status'] ) && 'running' === $state['status'] ) { wp_send_json_error( array( 'message' => __( 'A backup is already in progress.', 'uxpack-basic' ) ) ); } if ( class_exists( 'UXPack_Restore', false ) && UXPack_Restore::is_running() ) { wp_send_json_error( array( 'message' => __( 'A restore is already in progress.', 'uxpack-basic' ) ) ); } $type = isset( $_POST['backup_type'] ) ? sanitize_text_field( wp_unslash( $_POST['backup_type'] ) ) : 'full'; $allowed_types = UXPack_Backup::get_allowed_backup_types(); if ( ! in_array( $type, $allowed_types, true ) ) { $type = 'full'; } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized via UXPack_Backup::sanitize_backup_label(). $label = isset( $_POST['backup_label'] ) ? UXPack_Backup::sanitize_backup_label( wp_unslash( $_POST['backup_label'] ) ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- backup password must not be altered by sanitize_text_field(). $password = isset( $_POST['backup_password'] ) ? (string) wp_unslash( $_POST['backup_password'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- backup password must not be altered by sanitize_text_field(). $password_confirm = isset( $_POST['backup_password_confirm'] ) ? (string) wp_unslash( $_POST['backup_password_confirm'] ) : ''; if ( ! class_exists( 'UXPack_Encryption', false ) || UXPack_Encryption::MODE_PER_BACKUP !== UXPack_Encryption::get_encryption_mode() ) { $password = ''; $password_confirm = ''; } $destinations = array( 'local' ); if ( isset( $_POST['destinations'] ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitized via UXPack_Remote_Storage::sanitize_destinations(). $raw_destinations = wp_unslash( $_POST['destinations'] ); if ( class_exists( 'UXPack_Remote_Storage', false ) ) { $destinations = UXPack_Remote_Storage::sanitize_destinations( $raw_destinations ); $dest_ok = UXPack_Remote_Storage::validate_destinations_for_run( $destinations ); if ( is_wp_error( $dest_ok ) ) { wp_send_json_error( array( 'message' => $dest_ok->get_error_message() ) ); } } } if ( function_exists( 'ignore_user_abort' ) ) { ignore_user_abort( true ); } // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- long-running backup/restore/download must not die mid-stream. @set_time_limit( 0 ); $last_touch = 0; $on_log = function () use ( &$last_touch ) { self::maybe_touch_backup_running_state( $last_touch, 20 ); }; $response_sent = false; $options = array( 'source' => 'manual', 'label' => $label, 'password' => $password, 'password_confirm' => $password_confirm, 'destinations' => $destinations, 'on_log' => $on_log, 'on_started' => function () use ( &$response_sent ) { if ( $response_sent ) { return; } $response_sent = true; self::send_backup_started_json_response(); }, ); if ( UXPack_Backup::should_use_chunked_backup( $type, 'manual' ) ) { $result = self::execute_chunked_backup_start( $type, $options ); self::ensure_backup_terminal_state( $result ); if ( ! $response_sent ) { if ( is_array( $result ) && ! empty( $result['success'] ) && empty( $result['continue'] ) ) { wp_send_json_success( self::backup_success_ajax_payload( $result ) ); } if ( is_array( $result ) && ! empty( $result['success'] ) && ! empty( $result['continue'] ) ) { self::send_backup_started_json_response(); exit; } $message = is_array( $result ) && isset( $result['message'] ) ? (string) $result['message'] : __( 'An error occurred.', 'uxpack-basic' ); wp_send_json_error( array( 'message' => $message ) ); } exit; } $result = self::execute_backup( $type, $options ); self::ensure_backup_terminal_state( $result ); if ( ! $response_sent ) { if ( is_array( $result ) && ! empty( $result['success'] ) ) { wp_send_json_success( self::backup_success_ajax_payload( $result ) ); } $message = is_array( $result ) && isset( $result['message'] ) ? (string) $result['message'] : __( 'An error occurred.', 'uxpack-basic' ); wp_send_json_error( array( 'message' => $message ) ); } exit; } /** * AJAX: Continue a chunked manual backup. */ public function ajax_continue_backup() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'run_backups' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } if ( function_exists( 'ignore_user_abort' ) ) { ignore_user_abort( true ); } // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- chunked backup steps must not die mid-stream. @set_time_limit( 0 ); $result = self::execute_chunked_backup_continue(); if ( ! empty( $result['cancelled'] ) ) { wp_send_json_success( array( 'status' => 'cancelled', 'message' => isset( $result['message'] ) ? (string) $result['message'] : __( 'Backup cancelled.', 'uxpack-basic' ), 'async' => false, ) ); } if ( ! empty( $result['success'] ) && ! empty( $result['continue'] ) ) { $state = self::get_backup_state_option_fresh(); wp_send_json_success( array( 'status' => 'running', 'async' => true, 'mode' => 'chunked', 'phase' => isset( $state['phase'] ) ? (string) $state['phase'] : ( ! empty( $result['not_ready'] ) ? 'db' : 'files' ), 'files_done' => isset( $state['files_done'] ) ? (int) $state['files_done'] : 0, 'files_total' => isset( $state['files_total'] ) ? (int) $state['files_total'] : 0, 'message' => isset( $result['message'] ) ? (string) $result['message'] : __( 'Backup in progress.', 'uxpack-basic' ), 'started' => isset( $state['started'] ) ? (int) $state['started'] : 0, 'not_ready' => ! empty( $result['not_ready'] ), ) ); } if ( ! empty( $result['success'] ) ) { wp_send_json_success( self::backup_success_ajax_payload( $result ) ); } wp_send_json_error( array( 'message' => isset( $result['message'] ) ? (string) $result['message'] : __( 'An error occurred.', 'uxpack-basic' ), 'status' => 'error', ) ); } /** * Start a chunked manual backup (first request). * * @param string $type Backup type. * @param array $options Options (same shape as execute_backup). * @return array */ public static function execute_chunked_backup_start( $type, $options = array() ) { $defaults = array( 'source' => 'manual', 'context' => '', 'label' => '', 'password' => '', 'password_confirm' => '', 'destinations' => array( 'local' ), 'on_log' => null, 'on_started' => null, ); $options = wp_parse_args( $options, $defaults ); if ( class_exists( 'UXPack_Remote_Storage', false ) ) { $options['destinations'] = UXPack_Remote_Storage::sanitize_destinations( $options['destinations'] ); $dest_ok = UXPack_Remote_Storage::validate_destinations_for_run( $options['destinations'] ); if ( is_wp_error( $dest_ok ) ) { return array( 'success' => false, 'message' => $dest_ok->get_error_message(), ); } } else { $options['destinations'] = array( 'local' ); } $type = UXPack_Backup::sanitize_backup_type( $type, 'full' ); if ( ! in_array( $type, array( 'full', 'db' ), true ) ) { $type = 'full'; } $email_context = array( 'type' => $type, 'source' => 'manual', 'source_context' => sanitize_key( (string) $options['context'] ), 'destinations' => $options['destinations'], ); self::cleanup_orphaned_backup_encrypt_temp_files(); if ( class_exists( 'UXPack_Preflight' ) && UXPack_Preflight::should_block_on_failure() ) { $preflight = UXPack_Preflight::run_for_backup(); if ( is_wp_error( $preflight ) ) { $msg = $preflight->get_error_message(); self::add_backup_log_entry( $msg, 'error' ); return array( 'success' => false, 'message' => $msg, ); } } $password = UXPack_Backup::resolve_run_backup_password( array( 'source' => 'manual', 'password' => (string) $options['password'], 'password_confirm' => (string) $options['password_confirm'], ) ); if ( is_wp_error( $password ) ) { $msg = $password->get_error_message(); self::add_backup_log_entry( $msg, 'error' ); return array( 'success' => false, 'message' => $msg, ); } $manifest_meta = self::build_backup_manifest_meta( $options ); if ( '' !== $password && class_exists( 'UXPack_Encryption', false ) ) { $manifest_meta['encrypted'] = true; $manifest_meta['encryption_method'] = UXPack_Encryption::get_encryption_method_key(); } self::set_backup_state( 'running', array( 'type' => $type, 'source' => 'manual', 'source_context' => $email_context['source_context'], 'destinations' => $options['destinations'], 'notification' => 'pending', 'mode' => 'chunked', 'phase' => 'db', 'files_done' => 0, 'files_total' => 0, 'cursor' => 0, 'chunk' => 0, ) ); if ( is_callable( $options['on_started'] ) ) { call_user_func( $options['on_started'] ); } $running_state = self::get_backup_state_option_fresh(); $email_context['started'] = isset( $running_state['started'] ) ? (int) $running_state['started'] : current_time( 'timestamp' ); self::store_chunk_password_transient( $email_context['started'], (string) $password ); $on_log = is_callable( $options['on_log'] ) ? $options['on_log'] : null; $last_touch = 0; $log_callback = function ( $message ) use ( $on_log, &$last_touch ) { if ( self::is_backup_cancel_requested() ) { throw new UXPack_Backup_Cancelled_Exception(); } if ( null !== $message && '' !== $message ) { self::add_backup_log_entry( $message, 'step', '' ); self::touch_backup_running_state(); $last_touch = time(); } elseif ( null === $message ) { self::maybe_touch_backup_running_state( $last_touch ); } if ( $on_log ) { $on_log( $message ); } }; if ( class_exists( 'UXPack_Optimize' ) && UXPack_Optimize::should_run() ) { try { UXPack_Optimize::run( $log_callback ); } catch ( UXPack_Backup_Cancelled_Exception $e ) { self::clear_chunk_password_transient( $email_context['started'] ); return self::finalize_backup_cancelled( $email_context, $type ); } } try { $result = UXPack_Backup::start_chunked_backup( $type, $log_callback, $manifest_meta, (string) $password ); } catch ( UXPack_Backup_Cancelled_Exception $e ) { self::clear_chunk_password_transient( $email_context['started'] ); return self::finalize_backup_cancelled( $email_context, $type ); } catch ( Throwable $e ) { $msg = UXPack_Backup::normalize_backup_error_message( $e->getMessage() ); self::clear_chunk_password_transient( $email_context['started'] ); self::add_backup_log_entry( $msg, 'error' ); self::set_backup_state( 'error', array( 'message' => $msg, 'type' => $type, 'source' => 'manual', 'started' => $email_context['started'], 'notification' => 'pending', ) ); return array( 'success' => false, 'message' => $msg, ); } if ( ! empty( $result['cancelled'] ) ) { self::clear_chunk_password_transient( $email_context['started'] ); return self::finalize_backup_cancelled( $email_context, $type ); } if ( empty( $result['success'] ) ) { $msg = isset( $result['message'] ) ? (string) $result['message'] : __( 'An error occurred.', 'uxpack-basic' ); self::clear_chunk_password_transient( $email_context['started'] ); self::add_backup_log_entry( $msg, 'error' ); self::set_backup_state( 'error', array( 'message' => $msg, 'type' => $type, 'source' => 'manual', 'started' => $email_context['started'], 'notification' => 'pending', ) ); return array( 'success' => false, 'message' => $msg, ); } if ( ! empty( $result['continue'] ) && ! empty( $result['state'] ) && is_array( $result['state'] ) ) { self::patch_backup_running_state( $result['state'] ); return $result; } // Completed in the start request (e.g. db-only). self::clear_chunk_password_transient( $email_context['started'] ); return self::complete_chunked_backup_success( $result, $email_context, $manifest_meta ); } /** * Run the next chunk of a chunked manual backup. * * @return array */ public static function execute_chunked_backup_continue() { $state = self::get_backup_state_option_fresh(); if ( empty( $state['status'] ) || 'running' !== $state['status'] || empty( $state['mode'] ) || 'chunked' !== $state['mode'] ) { return array( 'success' => false, 'message' => __( 'No chunked backup is in progress.', 'uxpack-basic' ), ); } if ( self::is_backup_cancel_requested() ) { $type = isset( $state['type'] ) ? (string) $state['type'] : 'full'; $email_context = array( 'type' => $type, 'source' => 'manual', 'started' => isset( $state['started'] ) ? (int) $state['started'] : current_time( 'timestamp' ), ); self::cleanup_running_backup_artifacts( $state ); return self::finalize_backup_cancelled( $email_context, $type ); } $started = isset( $state['started'] ) ? (int) $state['started'] : 0; $password = self::get_chunk_password_transient( $started ); $type = isset( $state['type'] ) ? (string) $state['type'] : 'full'; $email_context = array( 'type' => $type, 'source' => 'manual', 'started' => $started, 'destinations' => isset( $state['destinations'] ) ? $state['destinations'] : array( 'local' ), ); $manifest_meta = isset( $state['manifest_meta'] ) && is_array( $state['manifest_meta'] ) ? $state['manifest_meta'] : array(); $last_touch = 0; $log_callback = function ( $message ) use ( &$last_touch ) { if ( self::is_backup_cancel_requested() ) { throw new UXPack_Backup_Cancelled_Exception(); } if ( null !== $message && '' !== $message ) { self::add_backup_log_entry( $message, 'step', '' ); self::touch_backup_running_state(); $last_touch = time(); } elseif ( null === $message ) { self::maybe_touch_backup_running_state( $last_touch ); } }; try { $result = UXPack_Backup::continue_chunked_backup( $state, $log_callback, $password ); } catch ( UXPack_Backup_Cancelled_Exception $e ) { self::cleanup_running_backup_artifacts( $state ); self::clear_chunk_password_transient( $started ); return self::finalize_backup_cancelled( $email_context, $type ); } catch ( Throwable $e ) { $msg = UXPack_Backup::normalize_backup_error_message( $e->getMessage() ); self::clear_chunk_password_transient( $started ); self::add_backup_log_entry( $msg, 'error' ); self::set_backup_state( 'error', array( 'message' => $msg, 'type' => $type, 'source' => 'manual', 'started' => $started, 'notification' => 'pending', ) ); return array( 'success' => false, 'message' => $msg, ); } if ( ! empty( $result['cancelled'] ) ) { self::cleanup_running_backup_artifacts( $state ); self::clear_chunk_password_transient( $started ); return self::finalize_backup_cancelled( $email_context, $type ); } if ( empty( $result['success'] ) ) { $msg = isset( $result['message'] ) ? (string) $result['message'] : __( 'An error occurred.', 'uxpack-basic' ); self::clear_chunk_password_transient( $started ); self::add_backup_log_entry( $msg, 'error' ); self::set_backup_state( 'error', array( 'message' => $msg, 'type' => $type, 'source' => 'manual', 'started' => $started, 'notification' => 'pending', ) ); return array( 'success' => false, 'message' => $msg, ); } if ( ! empty( $result['not_ready'] ) ) { // Start request still preparing; keep stall timer fresh without failing the run. self::touch_backup_running_state(); return $result; } if ( ! empty( $result['continue'] ) && ! empty( $result['state'] ) && is_array( $result['state'] ) ) { self::patch_backup_running_state( $result['state'] ); return $result; } self::clear_chunk_password_transient( $started ); return self::complete_chunked_backup_success( $result, $email_context, $manifest_meta ); } /** * Mark a completed chunked backup as success (trim, notify, state). * * @param array $result Engine result. * @param array $email_context Email context. * @param array $manifest_meta Manifest meta. * @return array */ private static function complete_chunked_backup_success( $result, $email_context, $manifest_meta ) { $success_message = isset( $result['message'] ) ? $result['message'] : __( 'Backup completed successfully.', 'uxpack-basic' ); $success_file = isset( $result['filename'] ) ? $result['filename'] : ''; $type = isset( $email_context['type'] ) ? (string) $email_context['type'] : 'full'; $destinations = isset( $email_context['destinations'] ) ? $email_context['destinations'] : array( 'local' ); if ( class_exists( 'UXPack_Remote_Storage', false ) ) { $destinations = UXPack_Remote_Storage::sanitize_destinations( $destinations ); } else { $destinations = array( 'local' ); } self::add_backup_log_entry( $success_message, 'success', $success_file ); $result = self::attach_destination_uploads( array( 'success' => true, 'continue' => false, 'message' => $success_message, 'filename' => $success_file, ), array( 'source' => 'manual', 'destinations' => $destinations, ) ); self::set_backup_state( 'success', array( 'message' => $success_message, 'filename' => $success_file, 'type' => $type, 'source' => 'manual', 'destinations' => isset( $result['destinations'] ) ? $result['destinations'] : $destinations, 'keep_local' => isset( $result['keep_local'] ) ? (bool) $result['keep_local'] : true, 'delete_local_after' => ! empty( $result['delete_local_after'] ), 'remote_uploads' => isset( $result['remote_uploads'] ) ? $result['remote_uploads'] : array(), 'started' => isset( $email_context['started'] ) ? (int) $email_context['started'] : current_time( 'timestamp' ), 'notification' => 'pending', 'mode' => 'chunked', 'phase' => 'done', ) ); UXPack_Backup::trim_old_backups(); self::send_backup_notification( array_merge( $email_context, array( 'status' => 'success', 'message' => $success_message, 'filename' => $success_file, 'label' => isset( $manifest_meta['label'] ) ? (string) $manifest_meta['label'] : '', ) ) ); return $result; } /** * AJAX success payload after a finished local backup (includes remote upload handoff). * * @param array $result execute_backup / chunked success result. * @return array */ private static function backup_success_ajax_payload( $result ) { $payload = array( 'status' => 'success', 'message' => isset( $result['message'] ) ? (string) $result['message'] : '', 'async' => false, ); if ( isset( $result['filename'] ) ) { $payload['filename'] = (string) $result['filename']; } foreach ( array( 'destinations', 'keep_local', 'delete_local_after', 'remote_uploads', 'remote_upload_errors' ) as $key ) { if ( array_key_exists( $key, $result ) ) { $payload[ $key ] = $result[ $key ]; } } return $payload; } /** * Respond immediately so the HTTP request does not time out during long backups. */ private static function send_backup_started_json_response() { $running = self::get_backup_state_option_fresh(); $started = isset( $running['started'] ) ? (int) $running['started'] : current_time( 'timestamp' ); $payload = array( 'success' => true, 'data' => array( 'status' => 'running', 'message' => __( 'Backup started.', 'uxpack-basic' ), 'async' => true, 'started' => $started, 'mode' => isset( $running['mode'] ) ? (string) $running['mode'] : 'single', 'phase' => isset( $running['phase'] ) ? (string) $running['phase'] : '', 'files_done' => isset( $running['files_done'] ) ? (int) $running['files_done'] : 0, 'files_total' => isset( $running['files_total'] ) ? (int) $running['files_total'] : 0, ), ); $body = wp_json_encode( $payload ); if ( ! is_string( $body ) ) { wp_send_json_error( array( 'message' => __( 'An error occurred.', 'uxpack-basic' ) ) ); } while ( ob_get_level() > 0 ) { ob_end_clean(); } status_header( 200 ); nocache_headers(); header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) ); header( 'Content-Length: ' . strlen( $body ) ); echo $body; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON response. if ( function_exists( 'fastcgi_finish_request' ) ) { fastcgi_finish_request(); } else { flush(); } } /** * Add an entry to the backup log. The log is always written regardless of * whether the log block is visible in the UI. * * @param string $message Log message. * @param string $type Entry type: 'success', 'error', or 'step'. * @param string $filename Optional backup filename (e.g. for success entries). */ public static function add_backup_log_entry( $message, $type = 'error', $filename = '' ) { if ( (int) get_option( 'uxpack_enable_log', 1 ) !== 1 ) { return; } $allowed = array( 'success', 'error', 'step' ); $type = in_array( $type, $allowed, true ) ? $type : 'error'; $log = get_option( 'uxpack_error_log', array() ); if ( ! is_array( $log ) ) { $log = array(); } $filename = sanitize_file_name( (string) $filename ); // Attribute preceding untagged steps to this backup so delete/prune can remove the whole run. if ( '' !== $filename && ( 'success' === $type || 'error' === $type ) ) { for ( $i = count( $log ) - 1; $i >= 0; $i-- ) { if ( ! is_array( $log[ $i ] ) ) { break; } if ( ! empty( $log[ $i ]['filename'] ) ) { break; } $prev_type = isset( $log[ $i ]['type'] ) ? (string) $log[ $i ]['type'] : ''; if ( 'step' !== $prev_type ) { break; } $log[ $i ]['filename'] = $filename; } } $log[] = array( 'time' => current_time( 'timestamp' ), 'type' => $type, 'message' => wp_strip_all_tags( (string) $message ), 'filename' => $filename, ); // Keep only the latest entries (see get_activity_log_max_entries()). $max_entries = self::get_activity_log_max_entries(); if ( count( $log ) > $max_entries ) { $log = array_slice( $log, -$max_entries ); } update_option( 'uxpack_error_log', $log ); } /** * Build a download URL for a backup ZIP. * * @param string $filename Backup filename. * @return string */ private function get_backup_download_url( $filename ) { return wp_nonce_url( admin_url( 'admin-post.php?action=uxpack_download&file=' . rawurlencode( $filename ) ), 'uxpack_download_' . $filename, 'nonce' ); } /** * Build a download URL for the installer of a specific backup ZIP. * * @param string $backup_filename Backup ZIP filename. * @return string */ private function get_installer_download_url( $backup_filename ) { $backup_filename = sanitize_file_name( (string) $backup_filename ); return wp_nonce_url( admin_url( 'admin-post.php?action=uxpack_download_installer&file=' . rawurlencode( $backup_filename ) ), 'uxpack_download_installer_' . $backup_filename, 'nonce' ); } /** * Parse a download filename from the request (basename only). * * @param string $raw Raw request value. * @return string */ public function parse_download_filename( $raw ) { return basename( wp_unslash( (string) $raw ) ); } /** * Resolve a validated file inside the backup storage directory. * * @param string $filename Basename. * @param callable $filename_validator Validation callback. * @return string|null Absolute real path or null when invalid. */ private function get_validated_storage_file_path( $filename, $filename_validator ) { if ( ! is_callable( $filename_validator ) || ! $filename_validator( $filename ) ) { return null; } $storage = UXPack_Backup::get_storage_path(); $filepath = $storage . '/' . $filename; if ( ! file_exists( $filepath ) || ! is_file( $filepath ) || ! is_readable( $filepath ) ) { return null; } $real_file = realpath( $filepath ); $real_base = realpath( $storage ); if ( false === $real_file || false === $real_base ) { return null; } $prefix = rtrim( $real_base, DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR; if ( strpos( $real_file, $prefix ) !== 0 ) { return null; } return $real_file; } /** * Stream an in-memory string as a file download. * * @param string $content File body. * @param string $filename Download filename. * @param string $content_type MIME type. */ private function stream_string_download( $content, $filename, $content_type ) { if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) { session_write_close(); } // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- long-running backup/restore/download must not die mid-stream. @set_time_limit( 0 ); if ( function_exists( 'ignore_user_abort' ) ) { ignore_user_abort( true ); } if ( function_exists( 'wp_raise_memory_limit' ) ) { wp_raise_memory_limit( 'admin' ); } if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); } // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- disable compression for reliable binary download streaming. @ini_set( 'zlib.output_compression', 'Off' ); if ( function_exists( 'wp_ob_end_flush_all' ) ) { wp_ob_end_flush_all(); } while ( ob_get_level() > 0 ) { ob_end_clean(); } $filesize = strlen( $content ); nocache_headers(); header( 'Content-Type: ' . $content_type ); header( 'Content-Disposition: attachment; filename="' . esc_attr( $filename ) . '"' ); header( 'Content-Length: ' . $filesize ); header( 'Content-Transfer-Encoding: binary' ); header( 'Accept-Ranges: bytes' ); header( 'Cache-Control: private, no-transform, no-store, must-revalidate' ); header( 'Pragma: no-cache' ); header( 'X-Content-Type-Options: nosniff' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary/download body. echo $content; exit; } /** * Stream a file download response. * * @param string $real_file Absolute file path. * @param string $filename Download filename. * @param string $content_type MIME type. * @param bool $delete_after Remove the file after streaming (temporary exports). */ public function stream_file_download( $real_file, $filename, $content_type, $delete_after = false ) { if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) { session_write_close(); } // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- long-running backup/restore/download must not die mid-stream. @set_time_limit( 0 ); if ( function_exists( 'ignore_user_abort' ) ) { ignore_user_abort( true ); } if ( function_exists( 'wp_raise_memory_limit' ) ) { wp_raise_memory_limit( 'admin' ); } if ( function_exists( 'apache_setenv' ) ) { @apache_setenv( 'no-gzip', '1' ); } // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged -- disable compression for reliable binary download streaming. @ini_set( 'zlib.output_compression', 'Off' ); if ( function_exists( 'wp_ob_end_flush_all' ) ) { wp_ob_end_flush_all(); } while ( ob_get_level() > 0 ) { ob_end_clean(); } $filesize = filesize( $real_file ); if ( false === $filesize ) { wp_die( esc_html__( 'File not found.', 'uxpack-basic' ) ); } nocache_headers(); header( 'Content-Type: ' . $content_type ); header( 'Content-Disposition: attachment; filename="' . esc_attr( $filename ) . '"' ); header( 'Content-Length: ' . $filesize ); header( 'Content-Transfer-Encoding: binary' ); header( 'Accept-Ranges: bytes' ); header( 'Cache-Control: private, no-transform, no-store, must-revalidate' ); header( 'Pragma: no-cache' ); header( 'X-Content-Type-Options: nosniff' ); $chunk_size = (int) apply_filters( 'uxpack_download_chunk_size', 8 * 1024 * 1024, $real_file, $filename ); if ( $chunk_size < 1024 * 1024 ) { $chunk_size = 1024 * 1024; } // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_readfile,WordPress.WP.AlternativeFunctions.file_system_operations_fread,WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- streaming large backup downloads; WP_Filesystem cannot stream efficiently. $handle = fopen( $real_file, 'rb' ); if ( false === $handle ) { readfile( $real_file ); if ( $delete_after ) { wp_delete_file( $real_file ); } exit; } while ( ! feof( $handle ) ) { $chunk = fread( $handle, $chunk_size ); if ( false === $chunk || '' === $chunk ) { break; } echo $chunk; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary stream. if ( function_exists( 'flush' ) ) { flush(); } } fclose( $handle ); // phpcs:enable WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_readfile,WordPress.WP.AlternativeFunctions.file_system_operations_fread,WordPress.WP.AlternativeFunctions.file_system_operations_fclose if ( $delete_after ) { wp_delete_file( $real_file ); } exit; } /** * Handle backup file download. */ public function handle_download() { if ( ! UXPack_Capabilities::current_user_can( 'view_backups' ) ) { wp_die( esc_html__( 'Permission denied.', 'uxpack-basic' ) ); } $state = self::get_backup_state(); if ( isset( $state['status'] ) && 'running' === $state['status'] ) { wp_die( esc_html__( 'Cannot download backups while a backup is in progress.', 'uxpack-basic' ) ); } if ( class_exists( 'UXPack_Restore', false ) && UXPack_Restore::is_running() ) { wp_die( esc_html__( 'Cannot download backups while a restore is in progress.', 'uxpack-basic' ) ); } $nonce = isset( $_GET['nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['nonce'] ) ) : ''; $filename = isset( $_GET['file'] ) ? sanitize_file_name( wp_unslash( $_GET['file'] ) ) : ''; $filename = $this->parse_download_filename( $filename ); if ( '' === $filename || '' === $nonce || ! wp_verify_nonce( $nonce, 'uxpack_download_' . $filename ) ) { wp_die( esc_html__( 'Invalid request.', 'uxpack-basic' ) ); } $real_file = $this->get_validated_storage_file_path( $filename, 'UXPack_Backup::is_valid_backup_filename' ); if ( null === $real_file ) { wp_die( esc_html__( 'File not found.', 'uxpack-basic' ) ); } $this->stream_file_download( $real_file, $filename, 'application/zip' ); } /** * Handle installer file download. */ public function handle_download_installer() { if ( ! UXPack_Capabilities::current_user_can( 'view_backups' ) ) { wp_die( esc_html__( 'Permission denied.', 'uxpack-basic' ) ); } $state = self::get_backup_state(); if ( isset( $state['status'] ) && 'running' === $state['status'] ) { wp_die( esc_html__( 'Cannot download backups while a backup is in progress.', 'uxpack-basic' ) ); } if ( class_exists( 'UXPack_Restore', false ) && UXPack_Restore::is_running() ) { wp_die( esc_html__( 'Cannot download backups while a restore is in progress.', 'uxpack-basic' ) ); } $nonce = isset( $_GET['nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['nonce'] ) ) : ''; $backup_filename = isset( $_GET['file'] ) ? sanitize_file_name( wp_unslash( $_GET['file'] ) ) : ''; $backup_filename = $this->parse_download_filename( $backup_filename ); if ( '' === $backup_filename || '' === $nonce || ! wp_verify_nonce( $nonce, 'uxpack_download_installer_' . $backup_filename ) ) { wp_die( esc_html__( 'Invalid request.', 'uxpack-basic' ) ); } if ( ! UXPack_Backup::is_valid_backup_filename( $backup_filename ) || 0 === strpos( $backup_filename, 'uxpack-db-' ) ) { wp_die( esc_html__( 'File not found.', 'uxpack-basic' ) ); } $storage = UXPack_Backup::get_storage_path(); $backup_path = $storage . '/' . $backup_filename; if ( ! is_readable( $backup_path ) || ! is_file( $backup_path ) ) { wp_die( esc_html__( 'File not found.', 'uxpack-basic' ) ); } $installer_filename = UXPack_Backup::get_installer_filename(); // Never persist installer PHP when disk writes are skipped (WordPress.org Basic). if ( UXPack_Backup::should_skip_installer_disk_write() ) { try { $php = UXPack_Backup::get_installer_php_content( $backup_filename ); } catch ( Throwable $e ) { wp_die( esc_html__( 'Could not create the installer.', 'uxpack-basic' ) ); } if ( '' === $php ) { wp_die( esc_html__( 'Could not create the installer.', 'uxpack-basic' ) ); } $this->stream_string_download( $php, $installer_filename, 'application/x-php' ); return; } try { UXPack_Backup::create_installer_for_backup( $backup_filename ); } catch ( Throwable $e ) { wp_die( esc_html__( 'Could not create the installer.', 'uxpack-basic' ) ); } $real_file = $this->get_validated_storage_file_path( $installer_filename, 'UXPack_Backup::is_valid_installer_filename' ); if ( null === $real_file ) { wp_die( esc_html__( 'File not found.', 'uxpack-basic' ) ); } $this->stream_file_download( $real_file, $installer_filename, 'application/x-php' ); } /** * AJAX: Delete backup. */ public function ajax_delete_backup() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'delete_backups' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } $state = self::get_backup_state(); if ( isset( $state['status'] ) && 'running' === $state['status'] ) { wp_send_json_error( array( 'message' => __( 'Cannot delete backups while a backup is in progress.', 'uxpack-basic' ) ) ); } if ( class_exists( 'UXPack_Restore', false ) && UXPack_Restore::is_running() ) { wp_send_json_error( array( 'message' => __( 'Cannot delete backups while a restore is in progress.', 'uxpack-basic' ) ) ); } $filename = isset( $_POST['filename'] ) ? sanitize_file_name( wp_unslash( $_POST['filename'] ) ) : ''; if ( empty( $filename ) ) { wp_send_json_error( array( 'message' => __( 'Invalid filename.', 'uxpack-basic' ) ) ); } if ( ! UXPack_Backup::is_valid_backup_filename( $filename ) ) { wp_send_json_error( array( 'message' => __( 'Invalid filename.', 'uxpack-basic' ) ) ); } $delete_block = UXPack_Backup::get_delete_backup_block_message( $filename ); if ( '' !== $delete_block ) { wp_send_json_error( array( 'message' => $delete_block ) ); } if ( UXPack_Backup::delete_backup( $filename ) ) { wp_send_json_success(); } else { wp_send_json_error( array( 'message' => __( 'Could not delete backup.', 'uxpack-basic' ) ) ); } } /** * AJAX: Bulk delete backups. */ public function ajax_bulk_delete_backup() { check_ajax_referer( 'uxpack_backup', 'nonce' ); if ( ! UXPack_Capabilities::current_user_can( 'delete_backups' ) ) { wp_send_json_error( array( 'message' => __( 'Permission denied.', 'uxpack-basic' ) ) ); } $state = self::get_backup_state(); if ( isset( $state['status'] ) && 'running' === $state['status'] ) { wp_send_json_error( array( 'message' => __( 'Cannot delete backups while a backup is in progress.', 'uxpack-basic' ) ) ); } if ( class_exists( 'UXPack_Restore', false ) && UXPack_Restore::is_running() ) { wp_send_json_error( array( 'message' => __( 'Cannot delete backups while a restore is in progress.', 'uxpack-basic' ) ) ); } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each filename sanitized with sanitize_file_name() below. $raw_filenames = isset( $_POST['filenames'] ) ? wp_unslash( $_POST['filenames'] ) : array(); if ( ! is_array( $raw_filenames ) ) { $raw_filenames = '' !== (string) $raw_filenames ? array( (string) $raw_filenames ) : array(); } $filenames = array(); foreach ( $raw_filenames as $f ) { $f = sanitize_file_name( (string) $f ); if ( $f && UXPack_Backup::is_valid_backup_filename( $f ) ) { $filenames[] = $f; } } $filenames = array_values( array_unique( $filenames ) ); if ( empty( $filenames ) ) { wp_send_json_error( array( 'message' => __( 'No valid backups selected.', 'uxpack-basic' ) ) ); } $backups = UXPack_Backup::get_backups(); if ( class_exists( 'UXPack_Delta' ) && count( $filenames ) > 1 ) { $filenames = UXPack_Delta::sort_filenames_for_chain_deletion( $filenames, $backups ); } $pending_deletes = array_fill_keys( $filenames, true ); $deleted = 0; $failed = array(); foreach ( $filenames as $filename ) { if ( UXPack_Backup::delete_backup( $filename, $pending_deletes ) ) { ++$deleted; unset( $pending_deletes[ $filename ] ); continue; } $failed[] = $filename; } if ( 0 === $deleted ) { wp_send_json_error( array( 'message' => __( 'Could not delete the selected backups.', 'uxpack-basic' ), 'failed' => $failed, ) ); } $message = sprintf( /* translators: %d: number of backups deleted */ _n( '%d backup deleted.', '%d backups deleted.', $deleted, 'uxpack-basic' ), $deleted ); if ( ! empty( $failed ) ) { $message .= ' ' . sprintf( /* translators: %d: number of backups that could not be deleted */ _n( '%d backup could not be deleted.', '%d backups could not be deleted.', count( $failed ), 'uxpack-basic' ), count( $failed ) ); } wp_send_json_success( array( 'message' => $message, 'deleted' => $deleted, 'failed' => $failed, ) ); } /** * Export UXPack → Settings options as JSON. */ public function handle_export_settings() { if ( ! UXPack_Capabilities::current_user_can( 'manage_settings' ) ) { wp_die( esc_html__( 'Permission denied.', 'uxpack-basic' ) ); } check_admin_referer( 'uxpack_export_settings' ); // Directory Basic has no license fields; never honor a crafted include flag. $include_license = class_exists( 'UXPack_Admin_Pro', false ) && ! empty( $_POST['uxpack_export_include_license'] ); $payload = $this->build_settings_export_payload( $include_license ); $json = wp_json_encode( $payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ); if ( false === $json ) { wp_die( esc_html__( 'Could not export settings.', 'uxpack-basic' ) ); } nocache_headers(); if ( $include_license ) { header( 'Cache-Control: private, no-store, no-cache, must-revalidate' ); header( 'Pragma: no-cache' ); } header( 'Content-Type: application/json; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="uxpack-settings-' . gmdate( 'Y-m-d' ) . '.json"' ); echo $json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON attachment. exit; } /** * Import UXPack → Settings options from JSON. */ public function handle_import_settings() { if ( ! UXPack_Capabilities::current_user_can( 'manage_settings' ) ) { wp_die( esc_html__( 'Permission denied.', 'uxpack-basic' ) ); } check_admin_referer( 'uxpack_import_settings' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- upload validated inside parse_settings_import_file(). $file = isset( $_FILES['uxpack_settings_file'] ) ? $_FILES['uxpack_settings_file'] : null; $payload = $this->parse_settings_import_file( $file ); if ( is_wp_error( $payload ) ) { wp_safe_redirect( add_query_arg( array( 'page' => 'uxpack-settings', 'uxpack_settings_import_error' => 'invalid', ), admin_url( 'admin.php' ) ) ); exit; } $result = $this->import_settings_from_payload( $payload ); if ( is_wp_error( $result ) ) { wp_safe_redirect( add_query_arg( array( 'page' => 'uxpack-settings', 'uxpack_settings_import_error' => 'empty', ), admin_url( 'admin.php' ) ) ); exit; } wp_safe_redirect( add_query_arg( array( 'page' => 'uxpack-settings', 'uxpack_settings_imported' => '1', 'uxpack_settings_import_count' => (int) $result, ), admin_url( 'admin.php' ) ) ); exit; } /** * Export the activity log as CSV. */ public function handle_export_activity_log() { if ( ! UXPack_Capabilities::current_user_can( 'view_log' ) ) { wp_die( esc_html__( 'Permission denied.', 'uxpack-basic' ) ); } if ( ! UXPack_License::can( UXPack_License::FEATURE_ACTIVITY_LOG_EXPORT ) ) { wp_die( esc_html( UXPack_License::get_upgrade_message() ) ); } check_admin_referer( 'uxpack_export_activity_log' ); $log = self::get_activity_log_entries(); nocache_headers(); header( 'Content-Type: text/csv; charset=utf-8' ); header( 'Content-Disposition: attachment; filename="uxpack-activity-log-' . gmdate( 'Y-m-d' ) . '.csv"' ); // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- CSV stream to browser via php://output. $output = fopen( 'php://output', 'w' ); if ( false === $output ) { wp_die( esc_html__( 'Could not export activity log.', 'uxpack-basic' ) ); } fputcsv( $output, array( __( 'Time', 'uxpack-basic' ), __( 'Status', 'uxpack-basic' ), __( 'Message', 'uxpack-basic' ), __( 'Backup file', 'uxpack-basic' ), ) ); foreach ( array_reverse( $log ) as $entry ) { if ( ! is_array( $entry ) ) { continue; } $timestamp = isset( $entry['time'] ) ? (int) $entry['time'] : 0; $type = isset( $entry['type'] ) ? (string) $entry['type'] : 'error'; $status = 'success' === $type ? __( 'Success', 'uxpack-basic' ) : ( 'step' === $type ? __( 'Step', 'uxpack-basic' ) : __( 'Error', 'uxpack-basic' ) ); fputcsv( $output, array( $timestamp > 0 ? gmdate( 'Y-m-d H:i:s', $timestamp ) : '', $status, isset( $entry['message'] ) ? (string) $entry['message'] : '', isset( $entry['filename'] ) ? (string) $entry['filename'] : '', ) ); } fclose( $output ); // phpcs:enable WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose exit; } }