settings = $settings; $this->generator = $generator; } /** * Hooks. Kept out of the constructor like Audio::register_hooks(). */ public function register_hooks() { add_action( 'transition_post_status', array($this, 'maybe_schedule'), 10, 3 ); add_action( self::HOOK, array($this, 'run') ); add_action( 'aifi_after_generate', array($this, 'clear_state'), 10, 2 ); // A featured image set by any other means replaces a pending or failed automatic one. // set_post_thumbnail() has no action of its own: it writes _thumbnail_id through these. add_action( 'added_post_meta', array($this, 'clear_state_on_thumbnail'), 10, 4 ); add_action( 'updated_post_meta', array($this, 'clear_state_on_thumbnail'), 10, 4 ); } /** * Whether the site has the feature switched on and may use it. * * @return bool */ public function is_enabled() { $settings = $this->settings->get_settings(); return Providers::can_use_premium() && !empty( $settings['auto_generate_on_publish'] ); } /** * Schedules the image when a post is first published without one. * * @param string $new_status New status. * @param string $old_status Old status. * @param \WP_Post $post Post. */ public function maybe_schedule( $new_status, $old_status, $post ) { if ( 'publish' !== $new_status || 'publish' === $old_status || !$post instanceof \WP_Post ) { return; } if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) { return; } if ( 'new' === $old_status && !$this->is_editor_insert( $post ) ) { return; } if ( wp_is_post_revision( $post ) || wp_is_post_autosave( $post ) ) { return; } if ( !in_array( $post->post_type, $this->settings->get_enabled_post_types(), true ) || !$this->is_enabled() ) { return; } if ( has_post_thumbnail( $post ) ) { return; } $queued = wp_next_scheduled( self::HOOK, array($post->ID) ); if ( false !== $queued ) { // A job that cron never ran may be queued again; a live one is left alone. if ( !self::is_stale( get_post_meta( $post->ID, self::META, true ) ) ) { return; } wp_unschedule_event( $queued, self::HOOK, array($post->ID) ); } $when = $this->next_slot(); wp_schedule_single_event( $when, self::HOOK, array($post->ID) ); $this->record( $post->ID, 'pending', '', $when ); // Ask cron to run once this request has finished. spawn_cron() does nothing when // DISABLE_WP_CRON is set, and then the server's real cron runs the event. if ( !$this->spawn_queued && !wp_doing_cron() ) { $this->spawn_queued = true; add_action( 'shutdown', 'spawn_cron' ); } } /** * Whether a post inserted straight as published comes from an editor, REST or MCP save. * * @param \WP_Post $post Post. * @return bool */ private function is_editor_insert( $post ) { global $pagenow; $allowed = defined( 'REST_REQUEST' ) && REST_REQUEST || is_admin() && in_array( $pagenow, array('post.php', 'post-new.php'), true ); /** * Filters whether a post inserted straight as published gets an automatic image. * * @param bool $allowed True for REST (editor, REST API, MCP) and admin editor saves. * @param \WP_Post $post The new post. */ return (bool) apply_filters( 'aifi_auto_generate_on_insert', $allowed, $post ); } /** * The time for the next job: now, or SPACING seconds after the last one. * * @return int Unix time. */ private function next_slot() { $slot = max( time(), (int) get_option( self::SLOT_OPTION, 0 ) ); update_option( self::SLOT_OPTION, $slot + self::SPACING, false ); return $slot; } /** * Cron callback: generates the featured image. * * @param int $post_id Post. */ public function run( $post_id ) { $post_id = (int) $post_id; if ( !Providers::can_use_premium() ) { $this->record( $post_id, 'failed', __( 'Auto-generate on publish is a Pro feature.', 'ai-featured-image-generator' ) ); return; } $this->record( $post_id, 'failed', __( 'Auto-generate on publish is a Pro feature.', 'ai-featured-image-generator' ) ); } /** * A generation from anywhere else replaces an old automatic result. * * @param int $attachment_id Attachment. * @param int $post_id Post. */ public function clear_state( $attachment_id, $post_id ) { if ( $post_id ) { delete_post_meta( (int) $post_id, self::META ); } } /** * A featured image set by other means clears a pending or failed automatic state. * * @param int $meta_id Meta row. * @param int $post_id Post. * @param string $meta_key Meta key. * @param mixed $meta_value New value. */ public function clear_state_on_thumbnail( $meta_id, $post_id, $meta_key, $meta_value ) { if ( '_thumbnail_id' !== $meta_key || !(int) $meta_value ) { return; } $state = get_post_meta( (int) $post_id, self::META, true ); if ( is_array( $state ) && isset( $state['status'] ) && in_array( $state['status'], array('pending', 'failed'), true ) ) { delete_post_meta( (int) $post_id, self::META ); } } /** * @param int $post_id Post. * @param string $status pending, done or failed. * @param string $message Reason for a failure. * @param int $due For pending: when the job is due to run (default now). */ private function record( $post_id, $status, $message = '', $due = 0 ) { $state = array( 'status' => $status, 'message' => wp_strip_all_tags( (string) $message ), 'time' => time(), ); if ( 'pending' === $status ) { $state['due'] = ( $due ? (int) $due : time() ); } update_post_meta( $post_id, self::META, $state ); } /** * Whether a stored state is a pending job more than STALE_AFTER seconds past its due time * (cron never ran it). * * @param mixed $state Stored meta value. * @return bool */ private static function is_stale( $state ) { if ( !is_array( $state ) || !isset( $state['status'] ) || 'pending' !== $state['status'] ) { return false; } $since = ( isset( $state['due'] ) ? (int) $state['due'] : (( isset( $state['time'] ) ? (int) $state['time'] : 0 )) ); return $since > 0 && time() - $since > self::STALE_AFTER; } /** * The stored result for a post. * * @param int $post_id Post. * A pending job more than 15 minutes past its due time is reported as failed, so the * screens stop saying "Generating" and the user can generate one by hand. * * @return array|null array( status, message, time ), or null when there is none. */ public static function state( $post_id ) { $state = get_post_meta( (int) $post_id, self::META, true ); if ( !is_array( $state ) || empty( $state['status'] ) ) { return null; } if ( self::is_stale( $state ) ) { $state['status'] = 'failed'; $state['message'] = self::stale_message(); $state['stale'] = true; } return $state; } /** * @return string Reason shown for a job that never started. */ private static function stale_message() { return __( 'It did not start within 15 minutes, so WP-Cron may not be running on this site. Use Generate to make one now.', 'ai-featured-image-generator' ); } /** * One sentence describing a stored result. * * @param array|null $state From state(). * @return string */ public static function state_text( $state ) { if ( !$state ) { return ''; } if ( self::is_stale( $state ) ) { $state['status'] = 'failed'; $state['message'] = self::stale_message(); } switch ( $state['status'] ) { case 'pending': return __( 'Generating a featured image automatically.', 'ai-featured-image-generator' ); case 'done': return __( 'Generated automatically when published.', 'ai-featured-image-generator' ); case 'failed': return ( '' !== (string) $state['message'] ? sprintf( __( 'Automatic image failed: %s', 'ai-featured-image-generator' ), $state['message'] ) : __( 'Automatic image failed.', 'ai-featured-image-generator' ) ); } return ''; } }