table_name = $wpdb->prefix . 'adminease_cron_viewer_log'; $this->settings = Plugin::get_settings( 'debug' ); add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] ); add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] ); add_action( 'adminease_settings_saved', [ $this, 'adminease_settings_saved' ] ); add_action( 'adminease_after_field_render', [ $this, 'adminease_after_field_render' ] ); if ( !empty( $this->settings['cron_viewer_log_enabled'] ) ) { add_action( 'init', [ $this, 'register_cron_logging_hooks' ], 1 ); add_action( 'adminease_cleanup_cron_viewer_logs', [ $this, 'cleanup_old_logs' ] ); add_action( 'wp_ajax_adminease_get_cron_scheduled_jobs', [ $this, 'ajax_get_cron_scheduled_jobs' ] ); add_action( 'wp_ajax_adminease_get_cron_execution_log', [ $this, 'ajax_get_cron_execution_log' ] ); add_action( 'wp_ajax_adminease_clear_cron_execution_log', [ $this, 'ajax_clear_cron_execution_log' ] ); add_action( 'wp_ajax_adminease_run_cron_job', [ $this, 'ajax_run_cron_job' ] ); add_action( 'wp_ajax_adminease_delete_cron_job', [ $this, 'ajax_delete_cron_job' ] ); add_action( 'wp_ajax_adminease_pause_cron_job', [ $this, 'ajax_pause_cron_job' ] ); add_action( 'wp_ajax_adminease_resume_cron_job', [ $this, 'ajax_resume_cron_job' ] ); add_action( 'wp_ajax_adminease_bulk_delete_cron_log', [ $this, 'ajax_bulk_delete_cron_log' ] ); if ( !wp_next_scheduled( 'adminease_cleanup_cron_viewer_logs' ) ) { wp_schedule_event( time(), 'hourly', 'adminease_cleanup_cron_viewer_logs' ); } } } /** * Registers cron execution logging hooks when running in a cron or WP-CLI context. * For each scheduled hook in _get_cron_array(), attaches before/after callbacks * to record execution time, memory usage, and status in the log table. * * @return void */ public function register_cron_logging_hooks(): void { $is_cron_context = ( defined( 'DOING_CRON' ) && DOING_CRON ) || ( defined( 'WP_CLI' ) && WP_CLI ); if ( !$is_cron_context ) { return; } $cron_array = _get_cron_array(); if ( empty( $cron_array ) ) { return; } foreach ( $cron_array as $timestamp => $hooks ) { foreach ( $hooks as $hook => $events ) { foreach ( $events as $event_key => $event ) { $args = $event['args'] ?? []; $schedule = $event['schedule'] ?? ''; $cron_interval = $event['interval'] ?? 0; add_action( $hook, function() use ( $hook, $event_key, $args, $schedule, $cron_interval ) { $this->before_cron_run( $hook, $event_key, $args, $schedule, $cron_interval ); }, PHP_INT_MIN ); add_action( $hook, function() use ( $hook, $event_key ) { $this->after_cron_run( $hook, $event_key ); }, PHP_INT_MAX ); } } } } /** * Called immediately before a cron hook fires. Inserts a 'processing' row * so that fatal crashes are visible as stuck entries in the log. * * @param string $hook The cron hook name. * @param string $event_key The md5 event key (hash of args). * @param array $args The hook arguments. * @param string $schedule Recurrence schedule slug. * @param int $cron_interval Interval in seconds. * * @return void */ public function before_cron_run( string $hook, string $event_key, array $args, string $schedule, int $cron_interval ): void { $log_id = $this->insert_log_entry( [ 'timestamp' => current_time( 'mysql' ), 'hook' => $hook, 'args' => wp_json_encode( $args ), 'schedule' => $schedule, 'cron_interval' => $cron_interval, 'execution_time' => null, 'memory_usage' => null, 'status' => 'processing', 'error_message' => null, ] ); if ( !isset( $this->hook_start_data[ $event_key ] ) ) { $this->hook_start_data[ $event_key ] = []; } $this->hook_start_data[ $event_key ][] = [ 'log_id' => $log_id, 'start_time' => microtime( true ), ]; } /** * Called immediately after a cron hook fires. Updates the log row * with execution time, peak memory usage, and success status. * * @param string $hook The cron hook name. * @param string $event_key The md5 event key. * * @return void */ public function after_cron_run( string $hook, string $event_key ): void { if ( empty( $this->hook_start_data[ $event_key ] ) ) { return; } $data = array_pop( $this->hook_start_data[ $event_key ] ); $execution_time = round( ( microtime( true ) - $data['start_time'] ) * 1000, 2 ); $memory_usage = memory_get_peak_usage( true ); $this->update_log_entry( $data['log_id'], 'success', $execution_time, $memory_usage ); $this->enforce_max_entries(); } /** * Adds settings fields for the Cron Viewer Log feature. * * @param array $fields Existing settings fields. * * @return array Modified settings fields. */ public function adminease_settings_fields( array $fields ): array { $max_entries = apply_filters( 'adminease_default_cron_viewer_log_max_entries', $this->settings['cron_viewer_log_max_entries'] ?? '1000' ); $fields['debug']['fields'][] = [ 'type' => 'switch', 'id' => 'cron-viewer-log-enabled', 'name' => 'adminease[debug][cron_viewer_log_enabled]', 'value' => $this->settings['cron_viewer_log_enabled'] ?? '', 'label_class' => 'adminease-switch', 'input_class' => 'form-control toggle-field', 'label' => __( 'Cron Viewer', 'adminease' ), 'description' => __( 'Manage and monitor all WordPress scheduled tasks (cron jobs). View all scheduled jobs, detect orphaned hooks left behind by deleted plugins, run jobs on demand, and review a full execution history including performance metrics.', 'adminease' ), 'child_fields' => [ [ 'type' => 'number', 'id' => 'cron-viewer-log-max-entries', 'name' => 'adminease[debug][cron_viewer_log_max_entries]', 'value' => $max_entries, 'label_class' => '', 'input_class' => 'form-control', 'wrapper_class' => 'form-group-child', 'label' => __( 'Maximum Log Entries', 'adminease' ), 'description' => __( 'Maximum number of execution history entries to keep (100-100000).', 'adminease' ), 'attributes' => [ 'data-parent' => 'cron-viewer-log-enabled', 'min' => '100', 'max' => $max_entries, ], ], [ 'type' => 'select', 'id' => 'cron-viewer-log-auto-clear', 'name' => 'adminease[debug][cron_viewer_log_auto_clear]', 'value' => $this->settings['cron_viewer_log_auto_clear'] ?? '7_days', 'label_class' => '', 'input_class' => 'form-control', 'wrapper_class' => 'form-group-child', 'label' => __( 'Auto Clear Logs After', 'adminease' ), 'description' => __( 'Automatically delete execution history older than this period.', 'adminease' ), 'options' => [ '1_hour' => __( '1 Hour', 'adminease' ), '24_hours' => __( '24 Hours', 'adminease' ), '7_days' => __( '7 Days', 'adminease' ), '30_days' => __( '30 Days', 'adminease' ), 'never' => __( 'Never', 'adminease' ), ], 'attributes' => [ 'data-parent' => 'cron-viewer-log-enabled', ], ], [ 'type' => 'switch', 'id' => 'cron-viewer-log-auto-load', 'name' => 'adminease[debug][cron_viewer_log_auto_load]', 'value' => $this->settings['cron_viewer_log_auto_load'] ?? false, 'label_class' => 'adminease-switch', 'input_class' => 'form-control', 'wrapper_class' => 'form-group-child', 'label' => __( 'Auto-Load Cron Viewer', 'adminease' ), 'field_description' => __( 'Automatically load cron jobs and execution log when the AdminEase admin page is opened.', 'adminease' ), 'attributes' => [ 'data-parent' => 'cron-viewer-log-enabled', ], ], ], ]; return $fields; } /** * Enqueues scripts and styles for the Cron Viewer Log on the AdminEase admin page. * * @param string $hook Current admin page hook. * * @return void */ public function admin_enqueue_scripts( string $hook ): void { if ( 'toplevel_page_adminease' !== $hook ) { return; } wp_enqueue_style( ADMINEASE_NAME . 'CronViewerLog', ADMINEASE_PLUGIN_URL . 'assets/css/AdminEaseCronViewerLog.css', [ ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/css/AdminEaseCronViewerLog.css' ) ); wp_enqueue_script( ADMINEASE_NAME . 'CronViewerLog', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseCronViewerLog.js', [ 'jquery', ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseCronViewerLog.js' ), true ); $security = [ 'getScheduledJobs' => wp_create_nonce( 'adminease_get_cron_scheduled_jobs' ), 'getExecutionLog' => wp_create_nonce( 'adminease_get_cron_execution_log' ), 'clearExecutionLog' => wp_create_nonce( 'adminease_clear_cron_execution_log' ), 'runCronJob' => wp_create_nonce( 'adminease_run_cron_job' ), 'deleteCronJob' => wp_create_nonce( 'adminease_delete_cron_job' ), 'pauseCronJob' => wp_create_nonce( 'adminease_pause_cron_job' ), 'resumeCronJob' => wp_create_nonce( 'adminease_resume_cron_job' ), 'bulkDeleteCronLog' => wp_create_nonce( 'adminease_bulk_delete_cron_log' ), ]; $i18n = [ 'confirmClearLog' => esc_html__( 'Are you sure you want to clear all execution history?', 'adminease' ), 'confirmDeleteJob' => esc_html__( 'Are you sure you want to unschedule this cron job?', 'adminease' ), 'confirmRunJob' => esc_html__( 'Are you sure you want to run this cron job now?', 'adminease' ), 'confirmPauseJob' => esc_html__( 'Are you sure you want to pause this cron job?', 'adminease' ), 'confirmBulkDelete' => esc_html__( 'Are you sure you want to delete the selected log entries?', 'adminease' ), 'selectEntriesFirst' => esc_html__( 'Please select at least one entry.', 'adminease' ), 'logEmpty' => esc_html__( 'No cron executions logged yet. Enable the feature and executions will appear here.', 'adminease' ), 'noScheduledJobs' => esc_html__( 'No scheduled cron jobs found.', 'adminease' ), 'logCleared' => esc_html__( 'Execution history cleared successfully.', 'adminease' ), 'jobDeleted' => esc_html__( 'Cron job unscheduled successfully.', 'adminease' ), 'jobPaused' => esc_html__( 'Cron job paused successfully.', 'adminease' ), 'jobResumed' => esc_html__( 'Cron job resumed successfully.', 'adminease' ), 'entriesDeleted' => esc_html__( 'Selected entries deleted successfully.', 'adminease' ), 'loadFailed' => esc_html__( 'Failed to load data.', 'adminease' ), 'clearFailed' => esc_html__( 'Failed to clear execution history.', 'adminease' ), 'deleteFailed' => esc_html__( 'Failed to delete cron job.', 'adminease' ), 'pauseFailed' => esc_html__( 'Failed to pause cron job.', 'adminease' ), 'resumeFailed' => esc_html__( 'Failed to resume cron job.', 'adminease' ), 'bulkDeleteFailed' => esc_html__( 'Failed to delete selected entries.', 'adminease' ), /* translators: 1: current page, 2: total pages */ 'paginationInfo' => esc_html__( 'Page %1$s of %2$s', 'adminease' ), /* translators: 1: start, 2: end, 3: total */ 'jobCount' => esc_html__( 'Showing %1$s-%2$s of %3$s jobs', 'adminease' ), /* translators: 1: start, 2: end, 3: total */ 'entryCount' => esc_html__( 'Showing %1$s-%2$s of %3$s entries', 'adminease' ), 'inSeconds' => esc_html__( 'in %d sec', 'adminease' ), 'secondsAgo' => esc_html__( '%d sec ago', 'adminease' ), 'inMinutes' => esc_html__( 'in %d min', 'adminease' ), 'minutesAgo' => esc_html__( '%d min ago', 'adminease' ), 'inHours' => esc_html__( 'in %d hr', 'adminease' ), 'hoursAgo' => esc_html__( '%d hr ago', 'adminease' ), 'inDays' => esc_html__( 'in %d days', 'adminease' ), 'daysAgo' => esc_html__( '%d days ago', 'adminease' ), 'runSuccess' => esc_html__( 'Cron job executed successfully in %s ms.', 'adminease' ), 'runFailed' => esc_html__( 'Failed to run cron job.', 'adminease' ), ]; wp_localize_script( ADMINEASE_NAME . 'CronViewerLog', ADMINEASE_NAME . 'CronViewerLogAjaxObj', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => $security, 'i18n' => $i18n, 'autoLoad' => !empty( $this->settings['cron_viewer_log_auto_load'] ), 'pluginUrl' => esc_url_raw( ADMINEASE_PLUGIN_URL ), ] ); } /** * Reloads settings and creates the DB table when the feature is saved as enabled. * * @param array $sanitized_settings Saved settings array. * * @return void */ public function adminease_settings_saved( array $sanitized_settings ): void { $this->settings = $sanitized_settings['debug'] ?? []; if ( !empty( $sanitized_settings['debug']['cron_viewer_log_enabled'] ) ) { $this->create_table(); } } /** * Renders the cron viewer partial after the toggle field is rendered. * * @param array $field The field being rendered. * * @return void */ public function adminease_after_field_render( array $field ): void { if ( 'cron-viewer-log-enabled' !== $field['id'] ) { return; } $settings = $this->settings; include_once ADMINEASE_DIR . 'partials/cron-viewer-log.php'; } // ------------------------------------------------------------------------- // Scheduled Jobs (live data from _get_cron_array) // ------------------------------------------------------------------------- /** * Returns a paginated, filtered list of all currently scheduled WP-Cron jobs. * Also merges in paused jobs stored in the adminease_paused_crons option. * Detects orphaned hooks (no registered callback) via has_action(). * * @param array $args { * Optional query args. * @type int $page Page number. Default 1. * @type int $per_page Items per page. Default 50. * @type string $search Filter by hook name (substring). Default ''. * @type bool $orphaned_only Only show orphaned hooks. Default false. * @type bool $hide_core Hide WP core hooks (wp_*, recovery_mode_*, etc). Default false. * @type bool $hide_action_scheduler Hide Action Scheduler hooks. Default false. * } * * @return array { 'jobs' => array, 'total' => int } */ public function get_scheduled_jobs( array $args = [] ): array { $cron_array = _get_cron_array(); $all_jobs = []; $now = time(); if ( !empty( $cron_array ) ) { foreach ( $cron_array as $timestamp => $hooks ) { foreach ( $hooks as $hook => $events ) { foreach ( $events as $event_key => $event ) { $all_jobs[] = [ 'timestamp' => (int) $timestamp, 'hook' => $hook, 'event_key' => $event_key, 'args' => $event['args'] ?? [], 'schedule' => $event['schedule'] ?? '', 'cron_interval' => $event['interval'] ?? 0, 'next_run' => (int) $timestamp, 'overdue' => (int) $timestamp < $now, 'has_callback' => (bool) has_action( $hook ), 'is_paused' => false, 'paused_at' => '', ]; } } } } // Apply search filter. $search = $args['search'] ?? ''; if ( !empty( $search ) ) { $all_jobs = array_values( array_filter( $all_jobs, function( $job ) use ( $search ) { return false !== stripos( $job['hook'], $search ); } ) ); } // Orphaned only. if ( !empty( $args['orphaned_only'] ) ) { $all_jobs = array_values( array_filter( $all_jobs, function( $job ) { return !$job['has_callback']; } ) ); } // Hide WP core hooks. if ( !empty( $args['hide_core'] ) ) { $core_prefixes = [ 'wp_', 'recovery_mode_', 'delete_expired_transients', 'wp_scheduled_' ]; $all_jobs = array_values( array_filter( $all_jobs, function( $job ) use ( $core_prefixes ) { foreach ( $core_prefixes as $prefix ) { if ( 0 === strpos( $job['hook'], $prefix ) ) { return false; } } return true; } ) ); } // Hide Action Scheduler hooks. if ( !empty( $args['hide_action_scheduler'] ) ) { $all_jobs = array_values( array_filter( $all_jobs, function( $job ) { return false === strpos( $job['hook'], 'action_scheduler' ); } ) ); } // Sort by next_run ASC (soonest first). usort( $all_jobs, function( $a, $b ) { return $a['next_run'] - $b['next_run']; } ); // Merge paused jobs. $paused_crons = get_option( 'adminease_paused_crons', [] ); foreach ( $paused_crons as $paused_job ) { if ( !empty( $search ) && false === stripos( $paused_job['hook'], $search ) ) { continue; } if ( !empty( $args['orphaned_only'] ) && has_action( $paused_job['hook'] ) ) { continue; } if ( !empty( $args['hide_core'] ) ) { $skip = false; foreach ( [ 'wp_', 'recovery_mode_', 'delete_expired_transients' ] as $prefix ) { if ( 0 === strpos( $paused_job['hook'], $prefix ) ) { $skip = true; break; } } if ( $skip ) { continue; } } if ( !empty( $args['hide_action_scheduler'] ) && false !== strpos( $paused_job['hook'], 'action_scheduler' ) ) { continue; } $all_jobs[] = [ 'timestamp' => 0, 'hook' => $paused_job['hook'], 'event_key' => $paused_job['event_key'], 'args' => $paused_job['args'] ?? [], 'schedule' => $paused_job['schedule'] ?? '', 'cron_interval' => $paused_job['cron_interval'] ?? 0, 'next_run' => 0, 'overdue' => false, 'has_callback' => (bool) has_action( $paused_job['hook'] ), 'is_paused' => true, 'paused_at' => $paused_job['paused_at'] ?? '', ]; } $total = count( $all_jobs ); $per_page = max( 1, (int) ( $args['per_page'] ?? 50 ) ); $page = max( 1, (int) ( $args['page'] ?? 1 ) ); $offset = ( $page - 1 ) * $per_page; $jobs = array_slice( $all_jobs, $offset, $per_page ); return [ 'jobs' => $jobs, 'total' => $total, ]; } /** * Renders the scheduled jobs HTML table. * * @param array $jobs Array of scheduled job data. * * @return string HTML table string, or empty string if no jobs. */ public function render_scheduled_jobs_table( array $jobs ): string { if ( empty( $jobs ) ) { return ''; } $wp_timezone = wp_timezone(); $date_format = get_option( 'date_format' ); $time_format = get_option( 'time_format' ); $datetime_format = $date_format . ' ' . $time_format; ob_start(); ?> 30 ? mb_substr( $args_encoded, 0, 30 ) . '...' : $args_encoded; $exact_time = $job['next_run'] > 0 ? wp_date( $datetime_format, $job['next_run'], $wp_timezone ) : '—'; ?>
(format_interval( (int) $job['cron_interval'] ) ); ?>)
50, 'page' => 1, 'status' => '', 'search' => '', 'hide_core' => false, 'hide_action_scheduler' => false, 'orderby' => 'timestamp', 'order' => 'DESC', ]; $args = wp_parse_args( $args, $defaults ); $allowed = [ 'timestamp', 'hook', 'execution_time', 'memory_usage', 'status' ]; $orderby = in_array( $args['orderby'], $allowed, true ) ? $args['orderby'] : 'timestamp'; $order = 'ASC' === strtoupper( $args['order'] ) ? 'ASC' : 'DESC'; $offset = ( (int) $args['page'] - 1 ) * (int) $args['per_page']; $where = []; $where_values = []; if ( !empty( $args['status'] ) ) { $where[] = 'status = %s'; $where_values[] = $args['status']; } if ( !empty( $args['search'] ) ) { $where[] = 'hook LIKE %s'; $where_values[] = '%' . $wpdb->esc_like( $args['search'] ) . '%'; } if ( !empty( $args['hide_core'] ) ) { $where[] = '( hook NOT LIKE %s AND hook NOT LIKE %s )'; $where_values[] = $wpdb->esc_like( 'wp_' ) . '%'; $where_values[] = $wpdb->esc_like( 'recovery_mode_' ) . '%'; } if ( !empty( $args['hide_action_scheduler'] ) ) { $where[] = 'hook NOT LIKE %s'; $where_values[] = $wpdb->esc_like( 'action_scheduler' ) . '%'; } $where_clause = !empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : ''; $params = array_merge( $where_values, [ (int) $args['per_page'], $offset ] ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $query = $wpdb->prepare( "SELECT * FROM {$this->table_name} {$where_clause} ORDER BY {$orderby} {$order} LIMIT %d OFFSET %d", $params ); // phpcs:enable // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared return $wpdb->get_results( $query, ARRAY_A ); } /** * Returns the total count of log entries matching the given filters. * * @param array $args Same filter args as get_log_entries(). * * @return int Total count. */ public function get_total_count( array $args = [] ): int { global $wpdb; $where = []; $where_values = []; if ( !empty( $args['status'] ) ) { $where[] = 'status = %s'; $where_values[] = $args['status']; } if ( !empty( $args['search'] ) ) { $where[] = 'hook LIKE %s'; $where_values[] = '%' . $wpdb->esc_like( $args['search'] ) . '%'; } if ( !empty( $args['hide_core'] ) ) { $where[] = '( hook NOT LIKE %s AND hook NOT LIKE %s )'; $where_values[] = $wpdb->esc_like( 'wp_' ) . '%'; $where_values[] = $wpdb->esc_like( 'recovery_mode_' ) . '%'; } if ( !empty( $args['hide_action_scheduler'] ) ) { $where[] = 'hook NOT LIKE %s'; $where_values[] = $wpdb->esc_like( 'action_scheduler' ) . '%'; } $where_clause = !empty( $where ) ? 'WHERE ' . implode( ' AND ', $where ) : ''; if ( empty( $where_values ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$this->table_name}" ); } // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $query = $wpdb->prepare( "SELECT COUNT(*) FROM {$this->table_name} {$where_clause}", $where_values ); // phpcs:enable // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared return (int) $wpdb->get_var( $query ); } /** * Renders the execution history HTML table. * * @param array $entries Array of log entry rows. * * @return string HTML string. */ public function render_cron_log_table( array $entries ): string { if ( empty( $entries ) ) { return ''; } ob_start(); ?> get_status_class( $entry['status'] ?? 'processing' ); $exec_time = isset( $entry['execution_time'] ) ? number_format_i18n( (float) $entry['execution_time'], 2 ) . ' ms' : '—'; $memory = isset( $entry['memory_usage'] ) ? $this->format_bytes( (int) $entry['memory_usage'] ) : '—'; $hook_short = mb_strlen( $entry['hook'] ) > 40 ? mb_substr( $entry['hook'], 0, 40 ) . '...' : $entry['hook']; ?>
insert( $this->table_name, [ 'timestamp' => $data['timestamp'], 'hook' => $data['hook'], 'args' => $data['args'], 'schedule' => $data['schedule'], 'cron_interval' => $data['cron_interval'], 'execution_time' => $data['execution_time'], 'memory_usage' => $data['memory_usage'], 'status' => $data['status'], 'error_message' => $data['error_message'], ], [ '%s', '%s', '%s', '%s', '%d', '%f', '%d', '%s', '%s' ] ); return (int) $wpdb->insert_id; } /** * Updates a log entry's status, execution time, and memory usage after a cron run. * * @param int $id Row ID to update. * @param string $status 'success', 'failed', or 'error'. * @param float $execution_time Execution duration in milliseconds. * @param int $memory_usage Peak memory in bytes. * * @return void */ private function update_log_entry( int $id, string $status, float $execution_time, int $memory_usage ): void { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Log status update $wpdb->update( $this->table_name, [ 'status' => $status, 'execution_time' => $execution_time, 'memory_usage' => $memory_usage, ], [ 'id' => $id ], [ '%s', '%f', '%d' ], [ '%d' ] ); } /** * Enforces the max entries limit by deleting the oldest rows. * * @return void */ private function enforce_max_entries(): void { global $wpdb; $max = $this->get_max_entries(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$this->table_name}" ); if ( $count > $max ) { $delete_count = $count - $max; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table_name} ORDER BY timestamp ASC LIMIT %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $delete_count ) ); } } /** * Deletes log entries older than the configured auto-clear period. * * @return void */ public function cleanup_old_logs(): void { $auto_clear = !empty( $this->settings['cron_viewer_log_auto_clear'] ) ? $this->settings['cron_viewer_log_auto_clear'] : '7_days'; if ( 'never' === $auto_clear ) { return; } global $wpdb; $time_map = [ '1_hour' => 3600, '24_hours' => 86400, '7_days' => 604800, '30_days' => 2592000, ]; $seconds = $time_map[ $auto_clear ] ?? 604800; $cutoff_time = gmdate( 'Y-m-d H:i:s', time() - $seconds ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table_name} WHERE timestamp < %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared $cutoff_time ) ); } /** * Truncates the execution log table. * * @return bool True on success. */ public function clear_log(): bool { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared return false !== $wpdb->query( "TRUNCATE TABLE {$this->table_name}" ); } /** * Returns the configured max entries setting. * * @return int */ private function get_max_entries(): int { return !empty( $this->settings['cron_viewer_log_max_entries'] ) ? (int) $this->settings['cron_viewer_log_max_entries'] : 1000; } /** * Creates the execution log DB table using dbDelta. * * @return void */ public function create_table(): void { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$this->table_name} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, timestamp datetime NOT NULL, hook varchar(255) NOT NULL, args longtext DEFAULT NULL, schedule varchar(100) DEFAULT NULL, cron_interval int(11) unsigned DEFAULT 0, execution_time float DEFAULT NULL, memory_usage bigint(20) unsigned DEFAULT NULL, status varchar(20) DEFAULT 'processing', error_message text DEFAULT NULL, PRIMARY KEY (id), KEY hook (hook), KEY timestamp (timestamp), KEY status (status) ) {$charset_collate};"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( $sql ); } /** * Drops the execution log table. * * @return void */ public function drop_table(): void { global $wpdb; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange $wpdb->query( "DROP TABLE IF EXISTS {$this->table_name}" ); } // ------------------------------------------------------------------------- // AJAX handlers // ------------------------------------------------------------------------- /** * AJAX: Returns the paginated, filtered list of scheduled cron jobs as HTML. * * @return void */ public function ajax_get_cron_scheduled_jobs(): void { if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_get_cron_scheduled_jobs' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if ( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $args = [ 'page' => isset( $_POST['page'] ) ? (int) $_POST['page'] : 1, 'per_page' => isset( $_POST['per_page'] ) ? (int) $_POST['per_page'] : 50, 'search' => isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '', 'orphaned_only' => !empty( $_POST['orphaned_only'] ), 'hide_core' => !empty( $_POST['hide_core'] ), 'hide_action_scheduler' => !empty( $_POST['hide_action_scheduler'] ), ]; $result = $this->get_scheduled_jobs( $args ); wp_send_json_success( [ 'table_html' => $this->render_scheduled_jobs_table( $result['jobs'] ), 'total' => $result['total'], 'page' => $args['page'], 'per_page' => $args['per_page'], ] ); } /** * AJAX: Returns the paginated, filtered execution history as HTML. * * @return void */ public function ajax_get_cron_execution_log(): void { if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_get_cron_execution_log' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if ( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $args = [ 'page' => isset( $_POST['page'] ) ? (int) $_POST['page'] : 1, 'per_page' => isset( $_POST['per_page'] ) ? (int) $_POST['per_page'] : 50, 'status' => isset( $_POST['status'] ) ? sanitize_text_field( wp_unslash( $_POST['status'] ) ) : '', 'search' => isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '', 'hide_core' => !empty( $_POST['hide_core'] ), 'hide_action_scheduler' => !empty( $_POST['hide_action_scheduler'] ), ]; $entries = $this->get_log_entries( $args ); $total = $this->get_total_count( $args ); $date_format = get_option( 'date_format' ); $time_format = get_option( 'time_format' ); $datetime_format = $date_format . ' ' . $time_format; foreach ( $entries as &$entry ) { $entry['formatted_time'] = date_i18n( $datetime_format, strtotime( $entry['timestamp'] ) ); } unset( $entry ); wp_send_json_success( [ 'table_html' => $this->render_cron_log_table( $entries ), 'total' => $total, 'page' => $args['page'], 'per_page' => $args['per_page'], ] ); } /** * AJAX: Clears all execution history entries. * * @return void */ public function ajax_clear_cron_execution_log(): void { if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_clear_cron_execution_log' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if ( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } if ( $this->clear_log() ) { wp_send_json_success( esc_html__( 'Execution history cleared successfully.', 'adminease' ) ); } else { wp_send_json_error( new WP_Error( 'clear_failed', __( 'Failed to clear execution history.', 'adminease' ) ) ); } } /** * AJAX: Runs a specific cron job immediately via do_action_ref_array(). * Defines DOING_CRON so that plugin callbacks that check it behave correctly. * * @return void */ public function ajax_run_cron_job(): void { if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_run_cron_job' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if ( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $hook = sanitize_text_field( wp_unslash( $_POST['hook'] ?? '' ) ); $event_key = sanitize_text_field( wp_unslash( $_POST['event_key'] ?? '' ) ); $timestamp = (int) ( $_POST['timestamp'] ?? 0 ); if ( empty( $hook ) ) { wp_send_json_error( new WP_Error( 'invalid_hook', __( 'Invalid hook name.', 'adminease' ) ) ); } // Resolve the exact args from the cron array so we call the right instance. $cron_array = _get_cron_array(); $args = []; if ( isset( $cron_array[ $timestamp ][ $hook ][ $event_key ] ) ) { $args = $cron_array[ $timestamp ][ $hook ][ $event_key ]['args']; } elseif ( !empty( $_POST['args'] ) ) { $decoded = json_decode( sanitize_text_field( wp_unslash( $_POST['args'] ) ), true ); if ( is_array( $decoded ) ) { $args = $decoded; } } // Define DOING_CRON so hooks that gate on it behave as expected. if ( !defined( 'DOING_CRON' ) ) { define( 'DOING_CRON', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound } $start_time = microtime( true ); do_action_ref_array( $hook, $args ); $execution_time = round( ( microtime( true ) - $start_time ) * 1000, 2 ); $memory_usage = memory_get_peak_usage( true ); // Log the manual run. $this->insert_log_entry( [ 'timestamp' => current_time( 'mysql' ), 'hook' => $hook, 'args' => wp_json_encode( $args ), 'schedule' => '', 'cron_interval' => 0, 'execution_time' => $execution_time, 'memory_usage' => $memory_usage, 'status' => 'success', 'error_message' => null, ] ); $this->enforce_max_entries(); wp_send_json_success( [ 'message' => esc_html__( 'Cron job executed successfully.', 'adminease' ), 'execution_time' => $execution_time, ] ); } /** * AJAX: Unschedules a specific cron job occurrence. * * @return void */ public function ajax_delete_cron_job(): void { if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_delete_cron_job' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if ( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $hook = sanitize_text_field( wp_unslash( $_POST['hook'] ?? '' ) ); $event_key = sanitize_text_field( wp_unslash( $_POST['event_key'] ?? '' ) ); $timestamp = (int) ( $_POST['timestamp'] ?? 0 ); $is_paused = !empty( $_POST['is_paused'] ); if ( empty( $hook ) ) { wp_send_json_error( new WP_Error( 'invalid_hook', __( 'Invalid hook name.', 'adminease' ) ) ); } // Handle paused jobs (stored in option, not cron array). if ( $is_paused ) { $paused_crons = get_option( 'adminease_paused_crons', [] ); $paused_crons = array_values( array_filter( $paused_crons, function( $job ) use ( $event_key ) { return $job['event_key'] !== $event_key; } ) ); update_option( 'adminease_paused_crons', $paused_crons ); wp_send_json_success( esc_html__( 'Paused cron job removed successfully.', 'adminease' ) ); } $cron_array = _get_cron_array(); if ( !isset( $cron_array[ $timestamp ][ $hook ][ $event_key ] ) ) { wp_send_json_error( new WP_Error( 'not_found', __( 'Cron job not found. It may have already been removed.', 'adminease' ) ) ); } $args = $cron_array[ $timestamp ][ $hook ][ $event_key ]['args']; $result = wp_unschedule_event( $timestamp, $hook, $args ); if ( false !== $result ) { wp_send_json_success( esc_html__( 'Cron job unscheduled successfully.', 'adminease' ) ); } else { wp_send_json_error( new WP_Error( 'delete_failed', __( 'Failed to unschedule cron job.', 'adminease' ) ) ); } } /** * AJAX: Pauses a cron job by unscheduling it and saving its data to an option. * * @return void */ public function ajax_pause_cron_job(): void { if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_pause_cron_job' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if ( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $hook = sanitize_text_field( wp_unslash( $_POST['hook'] ?? '' ) ); $event_key = sanitize_text_field( wp_unslash( $_POST['event_key'] ?? '' ) ); $timestamp = (int) ( $_POST['timestamp'] ?? 0 ); if ( empty( $hook ) ) { wp_send_json_error( new WP_Error( 'invalid_hook', __( 'Invalid hook name.', 'adminease' ) ) ); } $cron_array = _get_cron_array(); if ( !isset( $cron_array[ $timestamp ][ $hook ][ $event_key ] ) ) { wp_send_json_error( new WP_Error( 'not_found', __( 'Cron job not found.', 'adminease' ) ) ); } $event = $cron_array[ $timestamp ][ $hook ][ $event_key ]; wp_unschedule_event( $timestamp, $hook, $event['args'] ); $paused_crons = get_option( 'adminease_paused_crons', [] ); $paused_crons[] = [ 'hook' => $hook, 'event_key' => $event_key, 'args' => $event['args'] ?? [], 'schedule' => $event['schedule'] ?? '', 'cron_interval' => $event['interval'] ?? 0, 'paused_at' => current_time( 'mysql' ), ]; update_option( 'adminease_paused_crons', $paused_crons ); wp_send_json_success( esc_html__( 'Cron job paused successfully.', 'adminease' ) ); } /** * AJAX: Resumes a paused cron job by rescheduling it. * * @return void */ public function ajax_resume_cron_job(): void { if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_resume_cron_job' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if ( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $event_key = sanitize_text_field( wp_unslash( $_POST['event_key'] ?? '' ) ); if ( empty( $event_key ) ) { wp_send_json_error( new WP_Error( 'invalid_key', __( 'Invalid event key.', 'adminease' ) ) ); } $paused_crons = get_option( 'adminease_paused_crons', [] ); $job = null; $job_index = null; foreach ( $paused_crons as $i => $paused_job ) { if ( $paused_job['event_key'] === $event_key ) { $job = $paused_job; $job_index = $i; break; } } if ( null === $job ) { wp_send_json_error( new WP_Error( 'not_found', __( 'Paused cron job not found.', 'adminease' ) ) ); } if ( !empty( $job['schedule'] ) ) { wp_schedule_event( time(), $job['schedule'], $job['hook'], $job['args'] ); } else { wp_schedule_single_event( time(), $job['hook'], $job['args'] ); } array_splice( $paused_crons, $job_index, 1 ); update_option( 'adminease_paused_crons', $paused_crons ); wp_send_json_success( esc_html__( 'Cron job resumed successfully.', 'adminease' ) ); } /** * AJAX: Bulk deletes execution log entries by ID. * * @return void */ public function ajax_bulk_delete_cron_log(): void { if ( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_bulk_delete_cron_log' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'An error occurred. Refresh the page and try again.', 'adminease' ) ), 403 ); } if ( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', esc_html__( 'You do not have sufficient permissions to perform this action', 'adminease' ) ) ); } $ids = isset( $_POST['ids'] ) ? array_map( 'intval', (array) $_POST['ids'] ) : []; if ( empty( $ids ) ) { wp_send_json_error( new WP_Error( 'invalid_ids', __( 'No entry IDs provided.', 'adminease' ) ) ); } global $wpdb; $placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table_name} WHERE id IN ({$placeholders})", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $ids ) ); if ( false !== $deleted ) { wp_send_json_success( esc_html__( 'Selected entries deleted successfully.', 'adminease' ) ); } else { wp_send_json_error( new WP_Error( 'delete_failed', __( 'Failed to delete selected entries.', 'adminease' ) ) ); } } // ------------------------------------------------------------------------- // Utilities // ------------------------------------------------------------------------- /** * Returns the CSS badge class for a given status string. * * @param string $status Log entry status. * * @return string CSS class. */ private function get_status_class( string $status ): string { $map = [ 'success' => 'status-sent', 'failed' => 'status-failed', 'error' => 'status-failed', 'processing' => 'status-processing', ]; return $map[ $status ] ?? 'status-unknown'; } /** * Converts a number of seconds to a human-readable interval string. * * @param int $seconds Interval in seconds. * * @return string Human-readable string. */ private function format_interval( int $seconds ): string { if ( $seconds < 60 ) { /* translators: %d: number of seconds */ return sprintf( _n( '%d second', '%d seconds', $seconds, 'adminease' ), $seconds ); } if ( $seconds < 3600 ) { $minutes = (int) round( $seconds / 60 ); /* translators: %d: number of minutes */ return sprintf( _n( '%d minute', '%d minutes', $minutes, 'adminease' ), $minutes ); } if ( $seconds < 86400 ) { $hours = (int) round( $seconds / 3600 ); /* translators: %d: number of hours */ return sprintf( _n( '%d hour', '%d hours', $hours, 'adminease' ), $hours ); } $days = (int) round( $seconds / 86400 ); /* translators: %d: number of days */ return sprintf( _n( '%d day', '%d days', $days, 'adminease' ), $days ); } /** * Formats a byte count as a human-readable string (KB, MB, GB). * * @param int $bytes Byte count. * * @return string Formatted string. */ private function format_bytes( int $bytes ): string { if ( $bytes < 1024 ) { return $bytes . ' B'; } if ( $bytes < 1048576 ) { return number_format_i18n( $bytes / 1024, 1 ) . ' KB'; } if ( $bytes < 1073741824 ) { return number_format_i18n( $bytes / 1048576, 2 ) . ' MB'; } return number_format_i18n( $bytes / 1073741824, 2 ) . ' GB'; } }