get(); if ( ! $settings->has_consent() ) { return new \WP_Error( 'altlumen_consent', __( 'Give privacy consent for the selected provider in Altlumen Settings first.', 'altlumen' ) ); } $provider = $registry->get( $options['provider'] ); if ( ! $provider || ( $provider->requires_key() && '' === $settings->get_key( $provider->id() ) ) ) { return new \WP_Error( 'altlumen_auth', __( 'Connect a provider and save its key first.', 'altlumen' ) ); } return true; } /** * Read the persisted job state. * * @return array */ public function status(): array { return wp_parse_args( (array) get_option( 'altlumen_bulk_job', array() ), array( 'status' => 'idle', 'total' => 0, 'processed' => 0, 'errors' => 0, 'recent_errors' => array(), ) ); } /** * Create one authorized background job. * * @param array $ids Ids. * @param int $limit Limit. * @param string $source Source. * @param bool $missing Missing. * @return mixed */ public function start( array $ids = array(), int $limit = 0, string $source = 'bulk', bool $missing = true ) { if ( ! $this->authorized( $source, $ids ) ) { return new \WP_Error( 'altlumen_forbidden', __( 'You cannot manage generation jobs.', 'altlumen' ) ); } $ready = self::preflight(); if ( is_wp_error( $ready ) ) { return $ready; } $lock = Lock::acquire( 'altlumen_bulk_lock' ); if ( ! $lock ) { return $this->busy(); } try { if ( in_array( $this->status()['status'], array( 'running', 'paused', 'stopped' ), true ) ) { return new \WP_Error( 'altlumen_job_active', __( 'Resume or cancel the current job before starting another.', 'altlumen' ) ); } $options = ( new Settings( new Registry() ) )->get(); $state = array( 'id' => wp_generate_uuid4(), 'status' => 'running', 'total' => 0, 'processed' => 0, 'errors' => 0, 'started_at' => gmdate( 'c', Clock::now() ), 'finished_at' => '', 'actor' => get_current_user_id(), 'provider' => $options['provider'], 'source' => $source, 'missing' => $missing, 'ids' => array_values( array_unique( array_filter( array_map( 'absint', $ids ) ) ) ), 'max_id' => Candidates::max_id(), 'cursor' => 0, 'pending_id' => 0, 'attempt' => 0, 'auth_streak' => 0, 'sequence' => 0, 'not_before' => 0, 'recent_errors' => array(), 'notice' => '', ); $total = Candidates::select( $state, 0, 1, true ); $state['total'] = $limit > 0 ? min( $limit, $total ) : $total; if ( ! $state['total'] ) { return new \WP_Error( 'altlumen_no_images', __( 'No eligible images need processing.', 'altlumen' ) ); } $this->schedule( $state, RateLimiter::next() ); $this->save( $state ); return $state; } finally { $lock->release(); } } /** * Apply an explicit pause, resume or cancel action. * * @param string $action Action. * @return mixed */ public function control( string $action ) { if ( ! current_user_can( 'manage_options' ) ) { return new \WP_Error( 'altlumen_forbidden', __( 'You cannot manage generation jobs.', 'altlumen' ) ); } $lock = Lock::acquire( 'altlumen_bulk_lock' ); if ( ! $lock ) { return $this->busy(); } try { $state = $this->status(); if ( ! in_array( $state['status'], array( 'running', 'paused', 'stopped' ), true ) ) { return new \WP_Error( 'altlumen_no_job', __( 'There is no active job.', 'altlumen' ) ); } if ( 'resume' === $action ) { $ready = self::preflight(); if ( is_wp_error( $ready ) ) { return $ready; } $options = ( new Settings( new Registry() ) )->get(); $state['actor'] = get_current_user_id(); $state['provider'] = $options['provider']; $state['auth_streak'] = 0; $state['notice'] = ''; $state['status'] = 'running'; as_unschedule_all_actions( self::HOOK, null, 'altlumen' ); $this->schedule( $state, max( RateLimiter::next(), (int) $state['not_before'] ) ); } elseif ( 'pause' === $action ) { $state['status'] = 'paused'; as_unschedule_all_actions( self::HOOK, null, 'altlumen' ); } elseif ( 'cancel' === $action ) { $state['status'] = 'canceled'; $state['notice'] = ''; $state['finished_at'] = gmdate( 'c', Clock::now() ); as_unschedule_all_actions( self::HOOK, null, 'altlumen' ); } else { return new \WP_Error( 'altlumen_bad_action', __( 'Choose a valid job action.', 'altlumen' ) ); } $this->save( $state ); if ( 'canceled' === $state['status'] ) { do_action( 'altlumen_bulk_finished', $this->public_state( $state ) ); } return $state; } finally { $lock->release(); } } /** * Process one bounded unit of the current job. * * @param string $job_id Job id. * @param int $sequence Sequence. * @return void */ public function step( string $job_id, int $sequence ) { $lock = Lock::acquire( 'altlumen_bulk_lock' ); if ( ! $lock ) { as_schedule_single_action( Clock::now() + 1, self::HOOK, array( $job_id, $sequence ), 'altlumen' ); return; } $previous = get_current_user_id(); try { $state = $this->status(); if ( 'running' !== $state['status'] || ( $state['id'] ?? '' ) !== $job_id || ( $state['sequence'] ?? 0 ) !== $sequence ) { return; } wp_set_current_user( (int) $state['actor'] ); $ready = self::preflight(); $options = ( new Settings( new Registry() ) )->get(); if ( ! $this->authorized( $state['source'], $state['ids'] ) || is_wp_error( $ready ) || $options['provider'] !== $state['provider'] ) { $state['status'] = 'stopped'; $state['notice'] = 'altlumen_configuration'; $this->save( $state ); return; } if ( (int) $state['not_before'] > Clock::now() ) { $this->schedule( $state, (int) $state['not_before'] ); $this->save( $state ); return; } $id = (int) $state['pending_id']; if ( ! $id ) { $ids = Candidates::select( $state, (int) $state['cursor'] ); $id = $ids[0] ?? 0; } if ( ! $id || $state['processed'] >= $state['total'] ) { $this->finish( $state ); return; } $slot = RateLimiter::claim( (int) $options['batch_rate'] ); if ( $slot > Clock::now() ) { $state['pending_id'] = $id; $this->schedule( $state, $slot ); $this->save( $state ); return; } $registry = new Registry(); $settings = new Settings( $registry ); $inline = '__return_false'; add_filter( 'altlumen_inline_retries', $inline, PHP_INT_MAX ); try { $result = ( new Generator( $settings, $registry ) )->generate( $id, true, $state['source'] ); } catch ( \Throwable $error ) { $result = new \WP_Error( 'altlumen_bad_response', __( 'The image could not be processed.', 'altlumen' ) ); } finally { remove_filter( 'altlumen_inline_retries', $inline, PHP_INT_MAX ); } if ( is_wp_error( $result ) ) { $code = $this->safe_code( $result->get_error_code() ); /** Allow providers to pause without advancing the pending candidate. */ if ( apply_filters( 'altlumen_bulk_stop_on_error', false, $result, $state ) ) { $state['status'] = 'stopped'; $state['notice'] = $code; $state['recent_errors'][] = array( 'attachment_id' => $id, 'code' => $code, 'at' => gmdate( 'c', Clock::now() ), ); $state['recent_errors'] = array_slice( $state['recent_errors'], -10 ); $state['pending_id'] = $id; $this->save( $state ); return; } if ( in_array( $code, array( 'altlumen_rate_limit', 'altlumen_server' ), true ) && $state['attempt'] < 3 ) { $delays = array( 2, 8, 30 ); $data = $result->get_error_data(); $after = is_array( $data ) ? max( 0, (int) ( $data['retry_after'] ?? 0 ) ) : 0; $delay = max( $delays[ $state['attempt'] ], $after ); ++$state['attempt']; $state['pending_id'] = $id; $state['auth_streak'] = 0; $this->schedule( $state, max( RateLimiter::next(), Clock::now() + $delay ) ); $this->save( $state ); return; } ++$state['errors']; $state['recent_errors'][] = array( 'attachment_id' => $id, 'code' => $code, 'at' => gmdate( 'c', Clock::now() ), ); $state['recent_errors'] = array_slice( $state['recent_errors'], -10 ); $state['auth_streak'] = in_array( $code, array( 'altlumen_auth', 'altlumen_quota' ), true ) ? $state['auth_streak'] + 1 : 0; } else { $state['auth_streak'] = 0; } ++$state['processed']; $state['cursor'] = max( (int) $state['cursor'], $id ); $state['pending_id'] = 0; $state['attempt'] = 0; if ( $state['auth_streak'] >= 3 ) { $state['status'] = 'stopped'; $state['notice'] = 'altlumen_auth_quota'; $this->save( $state ); return; } if ( $state['processed'] >= $state['total'] ) { $this->finish( $state ); return; } $this->schedule( $state, RateLimiter::next() ); $this->save( $state ); } finally { wp_set_current_user( $previous ); $lock->release(); } } /** * Resolve the extension capability without broadening the default bulk API. * * @param string $source Processing origin. * @param array $ids Explicit image scope. * @return bool */ private function authorized( string $source, array $ids ): bool { $capability = apply_filters( 'altlumen_queue_capability', 'manage_options', $source, $ids ); if ( ! in_array( $capability, array( 'manage_options', 'upload_files' ), true ) || ! current_user_can( $capability ) ) { return false; } if ( 'upload_files' === $capability ) { if ( ! $ids ) { return false; } foreach ( $ids as $id ) { if ( ! wp_attachment_is_image( $id ) || ! current_user_can( 'edit_post', $id ) ) { return false; } } } return true; } /** * Expose only nonsecret progress fields. * * @param ?array $state State. * @return array */ public function public_state( ?array $state = null ): array { $state = $state ?? $this->status(); $public = array_intersect_key( $state, array_flip( array( 'id', 'status', 'total', 'processed', 'errors', 'started_at', 'finished_at', 'notice', 'recent_errors' ) ) ); foreach ( $public['recent_errors'] ?? array() as $index => $error ) { $id = (int) $error['attachment_id']; $thumbnail = wp_get_attachment_image_url( $id, 'thumbnail' ); $public['recent_errors'][ $index ]['thumbnail'] = $thumbnail ? esc_url_raw( $thumbnail ) : ''; $public['recent_errors'][ $index ]['edit_url'] = current_user_can( 'edit_post', $id ) ? get_edit_post_link( $id, 'raw' ) : ''; } return $public; } /** * Schedule the next sequence without sleeping. * * @param array $state State. * @param int $when When. * @return mixed */ private function schedule( array &$state, int $when ) { $state['not_before'] = $when; ++$state['sequence']; $state['action_id'] = as_schedule_single_action( $when, self::HOOK, array( $state['id'], $state['sequence'] ), 'altlumen', true ); if ( ! $state['action_id'] ) { $state['status'] = 'stopped'; $state['notice'] = 'altlumen_schedule'; } } /** * Persist completion and notify extensions once. * * @param array $state State. * @return mixed */ private function finish( array $state ) { $state['status'] = 'completed'; $state['notice'] = ''; $state['finished_at'] = gmdate( 'c', Clock::now() ); $this->save( $state ); do_action( 'altlumen_bulk_finished', $this->public_state( $state ) ); } /** * Persist non-autoloaded job state. * * @param array $state State. * @return void */ private function save( array $state ) { update_option( 'altlumen_bulk_job', $state, false ); } /** * Busy. * * @return mixed */ private function busy() { return new \WP_Error( 'altlumen_job_busy', __( 'The current image is processing. Try this action again shortly.', 'altlumen' ) ); } /** * Safe code. * * @param string $code Code. * @return string */ private function safe_code( string $code ): string { return in_array( $code, array( 'altlumen_auth', 'altlumen_quota', 'altlumen_rate_limit', 'altlumen_server', 'altlumen_timeout', 'altlumen_unsupported', 'altlumen_unsupported_type', 'altlumen_too_large', 'altlumen_low_quality', 'altlumen_refusal', 'altlumen_bad_response' ), true ) ? $code : 'altlumen_bad_response'; } }