cron_hook, array($this, 'process_scheduled_regeneration')); // Add custom cron intervals add_filter('cron_schedules', array($this, 'add_cron_intervals')); } /** * Schedule cron events. */ public function schedule_events() { $settings = get_option('aitm_settings', array()); if (empty($settings['auto_regenerate']) || !$settings['auto_regenerate']) { return; } $interval = $settings['cron_interval'] ?? 'daily'; if (!wp_next_scheduled($this->cron_hook)) { wp_schedule_event(time(), $interval, $this->cron_hook); } } /** * Clear cron events. */ public function clear_events() { wp_clear_scheduled_hook($this->cron_hook); } /** * Add custom cron intervals. * * @param array $schedules Existing cron schedules. * @return array */ public function add_cron_intervals($schedules) { $schedules['aitm_hourly'] = array( 'interval' => HOUR_IN_SECONDS, 'display' => __('Every Hour', 'ai-thumbnails-maker'), ); $schedules['aitm_every_6_hours'] = array( 'interval' => 6 * HOUR_IN_SECONDS, 'display' => __('Every 6 Hours', 'ai-thumbnails-maker'), ); $schedules['aitm_every_12_hours'] = array( 'interval' => 12 * HOUR_IN_SECONDS, 'display' => __('Every 12 Hours', 'ai-thumbnails-maker'), ); return $schedules; } /** * Process scheduled regeneration. */ public function process_scheduled_regeneration() { $settings = get_option('aitm_settings', array()); if (empty($settings['auto_regenerate'])) { return; } // Get attachments that need regeneration $attachments = $this->get_attachments_for_regeneration(); if (empty($attachments)) { return; } $batch_size = $settings['cron_batch_size'] ?? 10; $use_ai = $settings['cron_use_ai'] ?? false; $ai_service = $settings['cron_ai_service'] ?? ''; $processed = 0; $errors = 0; foreach ($attachments as $attachment_id) { if ($processed >= $batch_size) { break; } $regenerator = AITM_Regenerator::get_instance($attachment_id); if (is_wp_error($regenerator)) { $errors++; continue; } $result = $regenerator->regenerate($use_ai, $ai_service); if (is_wp_error($result)) { $errors++; } else { $processed++; } } // Log cron execution $this->log_cron_execution($processed, $errors, count($attachments)); } /** * Get attachments that need regeneration. * * @return array */ private function get_attachments_for_regeneration() { global $wpdb; $settings = get_option('aitm_settings', array()); $regeneration_interval = $settings['cron_regeneration_interval'] ?? 7; // days // Get attachments that haven't been regenerated recently $cutoff_date = gmdate('Y-m-d H:i:s', strtotime("-{$regeneration_interval} days")); $like_pattern = $wpdb->esc_like('image/') . '%'; $cache_key = 'aitm_cron_attachments_' . $regeneration_interval; $attachments = wp_cache_get($cache_key, 'aitm_cron'); if (false === $attachments) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Cron query with caching $attachments = $wpdb->get_col($wpdb->prepare( "SELECT DISTINCT p.ID FROM {$wpdb->posts} p LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_thumbnail_id' LEFT JOIN {$wpdb->prefix}aitm_statistics s ON p.ID = s.attachment_id WHERE p.post_type = 'attachment' AND p.post_mime_type LIKE %s AND ( s.created_at IS NULL OR s.created_at < %s OR s.success = 0 ) ORDER BY p.post_date DESC LIMIT 100", $like_pattern, $cutoff_date )); wp_cache_set($cache_key, $attachments, 'aitm_cron', 60); // Cache for 1 minute } return array_map('intval', $attachments); } /** * Log cron execution. * * @param int $processed Number of processed attachments. * @param int $errors Number of errors. * @param int $total Total attachments found. */ private function log_cron_execution($processed, $errors, $total) { $log_entry = array( 'timestamp' => current_time('mysql'), 'processed' => $processed, 'errors' => $errors, 'total' => $total, 'success_rate' => $total > 0 ? round(($processed / $total) * 100, 2) : 0, ); $cron_logs = get_option('aitm_cron_logs', array()); $cron_logs[] = $log_entry; // Keep only last 50 log entries if (count($cron_logs) > 50) { $cron_logs = array_slice($cron_logs, -50); } update_option('aitm_cron_logs', $cron_logs); } /** * Get cron execution logs. * * @param int $limit Number of log entries to return. * @return array */ public function get_cron_logs($limit = 20) { $cron_logs = get_option('aitm_cron_logs', array()); return array_slice(array_reverse($cron_logs), 0, $limit); } /** * Get next scheduled run time. * * @return int|false */ public function get_next_scheduled_run() { return wp_next_scheduled($this->cron_hook); } /** * Check if cron is scheduled. * * @return bool */ public function is_scheduled() { return wp_next_scheduled($this->cron_hook) !== false; } /** * Reschedule cron with new interval. * * @param string $interval New interval. * @return bool */ public function reschedule($interval) { $this->clear_events(); if (!wp_next_scheduled($this->cron_hook)) { return wp_schedule_event(time(), $interval, $this->cron_hook); } return true; } /** * Manually trigger regeneration for specific attachments. * * @param array $attachment_ids Attachment IDs to process. * @param bool $use_ai Whether to use AI. * @param string $ai_service AI service to use. * @return array */ public function manual_regeneration($attachment_ids, $use_ai = false, $ai_service = '') { $results = array( 'processed' => 0, 'errors' => 0, 'details' => array(), ); foreach ($attachment_ids as $attachment_id) { $regenerator = AITM_Regenerator::get_instance($attachment_id); if (is_wp_error($regenerator)) { $results['errors']++; $results['details'][] = array( 'attachment_id' => $attachment_id, 'success' => false, 'error' => $regenerator->get_error_message(), ); continue; } $result = $regenerator->regenerate($use_ai, $ai_service); if (is_wp_error($result)) { $results['errors']++; $results['details'][] = array( 'attachment_id' => $attachment_id, 'success' => false, 'error' => $result->get_error_message(), ); } else { $results['processed']++; $results['details'][] = array( 'attachment_id' => $attachment_id, 'success' => true, 'error' => null, ); } } return $results; } /** * Get cron status information. * * @return array */ public function get_cron_status() { $settings = get_option('aitm_settings', array()); $next_run = $this->get_next_scheduled_run(); $logs = $this->get_cron_logs(5); return array( 'enabled' => !empty($settings['auto_regenerate']), 'interval' => $settings['cron_interval'] ?? 'daily', 'next_run' => $next_run ? date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $next_run) : __('Not scheduled', 'ai-thumbnails-maker'), 'next_run_timestamp' => $next_run, 'is_scheduled' => $this->is_scheduled(), 'recent_logs' => $logs, 'batch_size' => $settings['cron_batch_size'] ?? 10, 'use_ai' => !empty($settings['cron_use_ai']), 'ai_service' => $settings['cron_ai_service'] ?? '', ); } /** * Clean up old cron logs. * * @param int $days Number of days to keep. * @return bool */ public function cleanup_old_logs($days = 30) { $cron_logs = get_option('aitm_cron_logs', array()); $cutoff_date = strtotime("-{$days} days"); $filtered_logs = array_filter($cron_logs, function($log) use ($cutoff_date) { return strtotime($log['timestamp']) > $cutoff_date; }); return update_option('aitm_cron_logs', array_values($filtered_logs)); } }