*/ public static function get_tasks() { return array( 'featured_image' => array( 'label' => __( 'Featured images', 'ai-content-generator-for-woocommerce' ), 'feature' => 'image_generation', 'review' => true, ), 'description' => array( 'label' => __( 'Descriptions', 'ai-content-generator-for-woocommerce' ), 'feature' => 'description', 'review' => true, ), 'seo_meta' => array( 'label' => __( 'SEO meta', 'ai-content-generator-for-woocommerce' ), 'feature' => WTOFE_SEO_Meta_Generator::FEATURE, 'review' => false, ), 'review_summary' => array( 'label' => __( 'Review summaries', 'ai-content-generator-for-woocommerce' ), 'feature' => '', 'review' => false, ), ); } /** * Whether a task's results wait for approval before reaching the product. * * @param string $task * @return bool */ public static function needs_review( $task ) { $tasks = self::get_tasks(); return ! empty( $tasks[ $task ]['review'] ); } /** * Whether a task can run with the current settings and active plugins. * * @param string $task * @return true|WP_Error */ public static function is_task_available( $task ) { $tasks = self::get_tasks(); if ( ! isset( $tasks[ $task ] ) ) { return new WP_Error( 'invalid_task', __( 'Unknown bulk action.', 'ai-content-generator-for-woocommerce' ) ); } if ( 'featured_image' === $task ) { return AI_Content_Generator_For_WooCommerce_Helper::can_generate_images(); } $provider = AI_Content_Generator_For_WooCommerce_Helper::describe_feature_provider( $tasks[ $task ]['feature'] ); if ( '' === $provider['provider'] ) { return AI_Content_Generator_For_WooCommerce_Helper::missing_provider_error( $tasks[ $task ]['feature'] ); } if ( 'seo_meta' === $task && ! WTOFE_SEO_Meta_Provider_Registry::is_any_active() ) { return new WP_Error( 'no_seo_plugin', __( 'No supported SEO plugin is active.', 'ai-content-generator-for-woocommerce' ) ); } if ( 'review_summary' === $task && ! WTOFE_Review_Summary_Generator::is_enabled() ) { return new WP_Error( 'review_summary_disabled', __( 'AI Review Summary is turned off in the plugin settings.', 'ai-content-generator-for-woocommerce' ) ); } return true; } /** * Normalises the options sent from the confirm dialog. * * @param string $task * @param array $raw Unslashed request values. * @return array{overwrite: bool, tone: string, fields: string[], force: bool} */ public static function normalize_options( $task, array $raw ) { $tones = AI_Content_Generator_For_WooCommerce_Helper::tone_instructions(); $tone = isset( $raw['tone'] ) ? sanitize_key( $raw['tone'] ) : 'formal'; $fields = isset( $raw['fields'] ) ? array_map( 'sanitize_key', (array) $raw['fields'] ) : array(); $fields = array_values( array_intersect( array( 'description', 'short_description' ), $fields ) ); return array( 'overwrite' => ! empty( $raw['overwrite'] ), 'tone' => isset( $tones[ $tone ] ) ? $tone : 'formal', 'fields' => $fields ? $fields : array( 'description', 'short_description' ), 'force' => ! empty( $raw['force'] ), ); } /** * Products per run for tasks that call the AI. 0 means no limit. * * @param string $task * @return int */ public static function get_max_products( $task ) { /** * Filters how many products one bulk run may send to the AI. * Return 0 to remove the limit. * * @param int $max * @param string $task featured_image, description, seo_meta or review_summary. */ return max( 0, (int) apply_filters( 'wtofe_bulk_max_products', self::DEFAULT_MAX_PRODUCTS, $task ) ); } // ------------------------------------------------------------------------- // Planning // ------------------------------------------------------------------------- /** * Splits the selected products into those to process and those skipped. * * @param string $task * @param int[] $product_ids * @param array $options From normalize_options(). * @return array{process: int[], skipped: array, over_limit: int[]} */ public static function plan( $task, array $product_ids, array $options ) { $plan = array( 'process' => array(), 'skipped' => array(), 'over_limit' => array() ); $max = self::get_max_products( $task ); foreach ( array_unique( array_map( 'absint', $product_ids ) ) as $product_id ) { $product = $product_id ? wc_get_product( $product_id ) : false; if ( ! $product || ! current_user_can( 'edit_product', $product_id ) ) { $plan['skipped'][ $product_id ] = __( 'You can\'t edit this product.', 'ai-content-generator-for-woocommerce' ); continue; } if ( self::is_queued( $task, $product_id ) ) { $plan['skipped'][ $product_id ] = __( 'Already queued in another run.', 'ai-content-generator-for-woocommerce' ); continue; } if ( self::is_awaiting_review( $task, $product_id ) ) { $plan['skipped'][ $product_id ] = __( 'Waiting for review in another run.', 'ai-content-generator-for-woocommerce' ); continue; } $reason = self::get_skip_reason( $task, $product, $options ); if ( '' !== $reason ) { $plan['skipped'][ $product_id ] = $reason; continue; } if ( $max && count( $plan['process'] ) >= $max ) { $plan['over_limit'][] = $product_id; continue; } $plan['process'][] = $product_id; } return $plan; } /** * AI requests the planned products will send, per provider and model. * * Descriptions use two features: products that only need a short * description go to the short-description model, which may be a * different provider. * * @param string $task * @param int[] $product_ids From plan()['process']. * @param array $options * @return array[] { count: int, provider: string, model: string } */ public static function count_requests( $task, array $product_ids, array $options ) { $tasks = self::get_tasks(); $requests = array(); foreach ( $product_ids as $product_id ) { $feature = $tasks[ $task ]['feature']; if ( 'description' === $task ) { $product = wc_get_product( $product_id ); if ( $product && ! in_array( 'description', self::get_description_fields_to_write( $product, $options ), true ) ) { $feature = 'short_description'; } } $provider = AI_Content_Generator_For_WooCommerce_Helper::describe_feature_provider( $feature ); $key = $provider['label'] . '|' . $provider['model']; if ( ! isset( $requests[ $key ] ) ) { $requests[ $key ] = array( 'count' => 0, 'provider' => $provider['label'], 'model' => $provider['model'] ); } ++$requests[ $key ]['count']; } return array_values( $requests ); } /** * Why a product doesn't need this task, or '' when it does. * * @param string $task * @param WC_Product $product * @param array $options * @return string */ private static function get_skip_reason( $task, $product, array $options ) { switch ( $task ) { case 'featured_image': if ( ! $options['overwrite'] && $product->get_image_id() ) { return __( 'Already has a featured image.', 'ai-content-generator-for-woocommerce' ); } break; case 'description': if ( ! self::get_description_fields_to_write( $product, $options ) ) { return __( 'Already has a description.', 'ai-content-generator-for-woocommerce' ); } break; case 'seo_meta': $provider = WTOFE_SEO_Meta_Provider_Registry::get_active_provider(); if ( $provider && ! $options['overwrite'] && '' !== trim( $provider->get_meta_title( $product->get_id() ) ) && '' !== trim( $provider->get_meta_description( $product->get_id() ) ) ) { return __( 'Already has an SEO title and meta description.', 'ai-content-generator-for-woocommerce' ); } break; case 'review_summary': $count = WTOFE_Review_Summary_Generator::get_approved_review_count( $product->get_id() ); $min = WTOFE_Review_Summary_Generator::get_min_reviews(); if ( $count < $min ) { return sprintf( /* translators: 1: approved review count, 2: required minimum. */ __( 'Not enough reviews (%1$d of %2$d required).', 'ai-content-generator-for-woocommerce' ), $count, $min ); } if ( ! $options['force'] && ! WTOFE_Review_Summary_Generator::needs_regeneration( $product->get_id() ) ) { return __( 'Summary is up to date.', 'ai-content-generator-for-woocommerce' ); } break; } return ''; } /** * The selected description fields this product would get written. * * @param WC_Product $product * @param array $options * @return string[] Subset of description, short_description. */ private static function get_description_fields_to_write( $product, array $options ) { if ( $options['overwrite'] ) { return $options['fields']; } $current = array( 'description' => $product->get_description(), 'short_description' => $product->get_short_description(), ); return array_values( array_filter( $options['fields'], function ( $field ) use ( $current ) { return '' === trim( wp_strip_all_tags( $current[ $field ] ) ); } ) ); } // ------------------------------------------------------------------------- // Batches // ------------------------------------------------------------------------- /** * Records skipped products, queues the rest, and adds the batch to the * current user's list. * * @param string $task * @param int[] $product_ids * @param array $options From normalize_options(). * @return string|WP_Error Batch ID. */ public static function start_batch( $task, array $product_ids, array $options ) { if ( ! function_exists( 'as_enqueue_async_action' ) ) { return new WP_Error( 'no_action_scheduler', __( 'Action Scheduler is not available. Update WooCommerce and try again.', 'ai-content-generator-for-woocommerce' ) ); } $available = self::is_task_available( $task ); if ( is_wp_error( $available ) ) { return $available; } $user_id = get_current_user_id(); $batch = strtolower( wp_generate_password( 12, false ) ); $plan = self::plan( $task, $product_ids, $options ); foreach ( $plan['skipped'] as $product_id => $reason ) { if ( $product_id ) { self::record_result( $product_id, $task, $batch, 'skipped', $reason ); } } foreach ( $plan['over_limit'] as $product_id ) { self::record_result( $product_id, $task, $batch, 'skipped', sprintf( /* translators: %d: products per run */ __( 'Over the limit of %d products per run. Run it again for the rest.', 'ai-content-generator-for-woocommerce' ), self::get_max_products( $task ) ) ); } foreach ( $plan['process'] as $product_id ) { self::queue_product( $batch, $task, $product_id, $user_id, $options ); } // A newer run of the same task replaces the old one's results, so // drop settled batches of that task from the list. $batches = self::get_user_batches( $user_id ); foreach ( $batches as $batch_id => $existing ) { if ( $task === $existing['task'] && self::is_settled( $batch_id, $existing ) ) { self::forget_batch( $batches, $batch_id ); } } $batches[ $batch ] = array( 'task' => $task, 'ids' => array_values( array_filter( array_map( 'absint', array_unique( $product_ids ) ) ) ), 'options' => $options, 'created' => time(), ); update_user_meta( $user_id, self::USER_META_BATCHES, $batches ); AI_Content_Generator_For_WooCommerce_Helper::log_debug( 'Bulk batch started', array( 'batch' => $batch, 'task' => $task, 'queued' => count( $plan['process'] ), 'skipped' => count( $plan['skipped'] ) + count( $plan['over_limit'] ), ) ); return $batch; } /** * Marks a product as queued and schedules its job. * * @param string $batch_id * @param string $task * @param int $product_id * @param int $user_id * @param array $options * @param string $message Shown while it waits, e.g. "Regenerating…". * @return void */ private static function queue_product( $batch_id, $task, $product_id, $user_id, array $options, $message = '' ) { self::record_result( $product_id, $task, $batch_id, 'queued', $message ); as_enqueue_async_action( self::HOOK, array( array( 'batch' => $batch_id, 'task' => $task, 'product_id' => $product_id, 'user_id' => $user_id, 'options' => $options, 'attempt' => 1, ) ), self::GROUP_PREFIX . $batch_id ); } /** * The user's batches, newest last. Batches past BATCH_TTL are dropped once * no job is left, along with any drafts nobody reviewed. * * @param int $user_id * @return array */ public static function get_user_batches( $user_id ) { $batches = get_user_meta( $user_id, self::USER_META_BATCHES, true ); if ( ! is_array( $batches ) ) { return array(); } $tasks = self::get_tasks(); $changed = false; foreach ( $batches as $batch_id => $batch ) { $stale = ! is_array( $batch ) || ! isset( $tasks[ $batch['task'] ?? '' ] ) || ( (int) ( $batch['created'] ?? 0 ) < time() - self::BATCH_TTL && ! self::is_running( $batch_id ) ); if ( $stale ) { self::forget_batch( $batches, $batch_id ); $changed = true; } } if ( $changed ) { update_user_meta( $user_id, self::USER_META_BATCHES, $batches ); } return $batches; } /** * Removes a settled batch from the user's list. * * @param int $user_id * @param string $batch_id * @return bool False when the batch is unknown, running, or has results waiting for review. */ public static function dismiss_batch( $user_id, $batch_id ) { $batches = self::get_user_batches( $user_id ); if ( ! isset( $batches[ $batch_id ] ) || ! self::is_settled( $batch_id, $batches[ $batch_id ] ) ) { return false; } self::forget_batch( $batches, $batch_id ); update_user_meta( $user_id, self::USER_META_BATCHES, $batches ); return true; } /** * Stops a running batch of the user's. Products already done keep their * changes and drafts stay reviewable; the job in progress (if any) still * finishes. * * @param int $user_id * @param string $batch_id * @return bool False when the batch is unknown. */ public static function cancel_batch( $user_id, $batch_id ) { $batches = self::get_user_batches( $user_id ); if ( ! isset( $batches[ $batch_id ] ) ) { return false; } self::abort( $batch_id, $batches[ $batch_id ]['task'], __( 'Cancelled.', 'ai-content-generator-for-woocommerce' ) ); return true; } /** * Whether a batch still has jobs pending or in progress. * * @param string $batch_id * @return bool */ public static function is_running( $batch_id ) { if ( ! function_exists( 'as_next_scheduled_action' ) ) { return false; } return false !== as_next_scheduled_action( self::HOOK, null, self::GROUP_PREFIX . $batch_id ); } /** * Whether a batch is over: no job left and nothing waiting for review. * * @param string $batch_id * @param array $batch * @return bool */ public static function is_settled( $batch_id, array $batch ) { if ( self::is_running( $batch_id ) ) { return false; } if ( ! self::needs_review( $batch['task'] ) ) { return true; } foreach ( $batch['ids'] as $product_id ) { $result = get_post_meta( $product_id, self::META_STATUS_PREFIX . $batch['task'], true ); if ( is_array( $result ) && $batch_id === ( $result['batch'] ?? '' ) && 'review' === ( $result['status'] ?? '' ) ) { return false; } } return true; } /** * Progress of one batch, for the Products screen notice. * * @param string $batch_id * @param array $batch From get_user_batches(). * @return array{ * task: string, review_task: bool, running: bool, settled: bool, stopped: array|null, * total: int, done: int, review: int, rejected: int, skipped: int, failed: int, * pending: int, cancelled: int, skip_reasons: array, failures: array[] * } */ public static function get_progress( $batch_id, array $batch ) { $running = self::is_running( $batch_id ); $stopped = get_option( self::OPTION_ABORT_PREFIX . $batch_id, null ); $meta_key = self::META_STATUS_PREFIX . $batch['task']; $progress = array( 'task' => $batch['task'], 'review_task' => self::needs_review( $batch['task'] ), 'running' => $running, 'settled' => false, 'stopped' => is_array( $stopped ) ? $stopped : null, 'total' => count( $batch['ids'] ), 'done' => 0, 'review' => 0, 'rejected' => 0, 'skipped' => 0, 'failed' => 0, 'pending' => 0, 'cancelled' => 0, 'skip_reasons' => array(), 'failures' => array(), ); update_meta_cache( 'post', $batch['ids'] ); foreach ( $batch['ids'] as $product_id ) { $result = get_post_meta( $product_id, $meta_key, true ); // Overwritten by a later run, or the product is gone. if ( ! is_array( $result ) || ( $result['batch'] ?? '' ) !== $batch_id ) { ++$progress['skipped']; continue; } $status = self::get_display_status( $result, $running, (bool) $progress['stopped'] ); if ( 'generating' === $status ) { $status = 'pending'; } elseif ( 'interrupted' === $status ) { // The job died without recording a result (fatal error, server timeout). $status = 'failed'; $result['message'] = __( 'Stopped before finishing. Check Tools → Scheduled Actions for details.', 'ai-content-generator-for-woocommerce' ); } ++$progress[ $status ]; if ( 'skipped' === $status ) { $reason = (string) $result['message']; $progress['skip_reasons'][ $reason ] = ( $progress['skip_reasons'][ $reason ] ?? 0 ) + 1; } elseif ( 'failed' === $status ) { $progress['failures'][] = array( 'product_id' => $product_id, 'message' => (string) $result['message'], 'links' => isset( $result['links'] ) ? (array) $result['links'] : array(), ); } } $progress['settled'] = ! $running && 0 === $progress['review']; return $progress; } /** * What a stored result means right now. * * @param array $result Product result meta. * @param bool $running Whether the batch still has jobs. * @param bool $stopped Whether the batch was stopped. * @return string done, review, rejected, skipped, failed, cancelled, generating or interrupted. */ private static function get_display_status( array $result, $running, $stopped ) { $status = (string) ( $result['status'] ?? '' ); if ( 'queued' === $status ) { if ( $running ) { return 'generating'; } return $stopped ? 'cancelled' : 'interrupted'; } return in_array( $status, array( 'done', 'review', 'rejected', 'skipped', 'failed', 'cancelled' ), true ) ? $status : 'skipped'; } /** * Forgets a batch: removes it from the list, deletes its stop reason, and * throws away drafts nobody reviewed. * * @param array $batches Passed by reference. * @param string $batch_id * @return void */ private static function forget_batch( array &$batches, $batch_id ) { $batch = $batches[ $batch_id ] ?? null; if ( is_array( $batch ) && self::needs_review( $batch['task'] ?? '' ) ) { foreach ( (array) $batch['ids'] as $product_id ) { $draft = self::get_draft( $batch['task'], $product_id ); if ( $draft && $batch_id === $draft['batch'] ) { self::discard_draft( $batch['task'], $product_id ); delete_post_meta( $product_id, self::META_STATUS_PREFIX . $batch['task'] ); } } } unset( $batches[ $batch_id ] ); delete_option( self::OPTION_ABORT_PREFIX . $batch_id ); } /** * Stops a batch: records why, cancels its pending jobs, and marks the * products still waiting as not processed. * * @param string $batch_id * @param string $task * @param string $message * @param array $links Fix links, see get_error_response_data(). * @return void */ private static function abort( $batch_id, $task, $message, array $links = array() ) { global $wpdb; update_option( self::OPTION_ABORT_PREFIX . $batch_id, array( 'message' => $message, 'links' => $links, 'time' => time(), ), false ); if ( function_exists( 'as_unschedule_all_actions' ) ) { as_unschedule_all_actions( '', array(), self::GROUP_PREFIX . $batch_id ); } $meta_key = self::META_STATUS_PREFIX . $task; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- finds this batch's products without the batch record. $product_ids = $wpdb->get_col( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value LIKE %s", $meta_key, '%' . $wpdb->esc_like( '"' . $batch_id . '"' ) . '%' ) ); foreach ( $product_ids as $product_id ) { $result = get_post_meta( $product_id, $meta_key, true ); if ( is_array( $result ) && $batch_id === ( $result['batch'] ?? '' ) && 'queued' === ( $result['status'] ?? '' ) ) { self::record_result( (int) $product_id, $task, $batch_id, 'cancelled', __( 'Not processed.', 'ai-content-generator-for-woocommerce' ) ); } } } /** * Whether a product is waiting in a running batch for this task. * * @param string $task * @param int $product_id * @return bool */ private static function is_queued( $task, $product_id ) { $result = get_post_meta( $product_id, self::META_STATUS_PREFIX . $task, true ); return is_array( $result ) && 'queued' === ( $result['status'] ?? '' ) && self::is_running( (string) $result['batch'] ); } /** * Whether a product has a draft for this task waiting for review. * * @param string $task * @param int $product_id * @return bool */ private static function is_awaiting_review( $task, $product_id ) { $result = get_post_meta( $product_id, self::META_STATUS_PREFIX . $task, true ); $draft = self::get_draft( $task, $product_id ); return is_array( $result ) && 'review' === ( $result['status'] ?? '' ) && $draft && $draft['batch'] === $result['batch']; } /** * Stores the latest result of a task for a product. * * @param int $product_id * @param string $task * @param string $batch_id * @param string $status queued, review, done, rejected, skipped, failed or cancelled. * @param string $message * @param array $links Fix links shown with a failure. * @return void */ private static function record_result( $product_id, $task, $batch_id, $status, $message = '', array $links = array() ) { update_post_meta( $product_id, self::META_STATUS_PREFIX . $task, array( 'batch' => $batch_id, 'status' => $status, 'message' => $message, 'links' => $links, 'time' => time(), ) ); } // ------------------------------------------------------------------------- // Drafts & review // ------------------------------------------------------------------------- /** * @param string $task * @param int $product_id * @return array|null { batch, time, image_url } or { batch, time, values }. */ private static function get_draft( $task, $product_id ) { $draft = get_post_meta( $product_id, self::META_DRAFT_PREFIX . $task, true ); return is_array( $draft ) && isset( $draft['batch'] ) ? $draft : null; } /** * @param string $task * @param int $product_id * @param string $batch_id * @param array $data image_url, or values keyed by field. * @return void */ private static function save_draft( $task, $product_id, $batch_id, array $data ) { self::discard_draft( $task, $product_id ); update_post_meta( $product_id, self::META_DRAFT_PREFIX . $task, array_merge( $data, array( 'batch' => $batch_id, 'time' => time(), ) ) ); } /** * Deletes a draft, and its image file for featured images. * * @param string $task * @param int $product_id * @return void */ private static function discard_draft( $task, $product_id ) { $draft = self::get_draft( $task, $product_id ); if ( $draft && ! empty( $draft['image_url'] ) ) { AI_Content_Generator_For_WooCommerce_Helper::discard_generated_images( array( $draft['image_url'] ) ); } delete_post_meta( $product_id, self::META_DRAFT_PREFIX . $task ); } /** * Approves, rejects or regenerates results of one of the user's batches. * * @param int $user_id * @param string $batch_id * @param string $op approve, reject or regenerate. * @param int[] $product_ids Empty for every product the operation applies to. * @return int[]|WP_Error Products that changed. A single requested product's error is returned as is. */ public static function review( $user_id, $batch_id, $op, array $product_ids = array() ) { $batches = self::get_user_batches( $user_id ); if ( ! isset( $batches[ $batch_id ] ) ) { return new WP_Error( 'unknown_batch', __( 'This bulk action no longer exists.', 'ai-content-generator-for-woocommerce' ) ); } $batch = $batches[ $batch_id ]; if ( ! self::needs_review( $batch['task'] ) || ! in_array( $op, array( 'approve', 'reject', 'regenerate' ), true ) ) { return new WP_Error( 'invalid_review', __( 'This action is not available here.', 'ai-content-generator-for-woocommerce' ) ); } $single = 1 === count( $product_ids ); $targets = $product_ids ? array_intersect( $batch['ids'], array_map( 'absint', $product_ids ) ) : $batch['ids']; $changed = array(); foreach ( $targets as $product_id ) { $result = self::review_product( $batch_id, $batch, $product_id, $op, $user_id ); if ( is_wp_error( $result ) ) { if ( $single ) { return $result; } continue; } $changed[] = $product_id; } if ( $single && ! $changed ) { return new WP_Error( 'not_in_batch', __( 'This product is not part of this bulk action.', 'ai-content-generator-for-woocommerce' ) ); } return $changed; } /** * @param string $batch_id * @param array $batch * @param int $product_id * @param string $op * @param int $user_id * @return true|WP_Error */ private static function review_product( $batch_id, array $batch, $product_id, $op, $user_id ) { $task = $batch['task']; $result = get_post_meta( $product_id, self::META_STATUS_PREFIX . $task, true ); if ( ! is_array( $result ) || $batch_id !== ( $result['batch'] ?? '' ) ) { return new WP_Error( 'stale', __( 'A newer bulk action has replaced this result.', 'ai-content-generator-for-woocommerce' ) ); } if ( ! current_user_can( 'edit_product', $product_id ) ) { return new WP_Error( 'forbidden', __( 'You can\'t edit this product.', 'ai-content-generator-for-woocommerce' ) ); } $status = self::get_display_status( $result, self::is_running( $batch_id ), (bool) get_option( self::OPTION_ABORT_PREFIX . $batch_id ) ); if ( 'regenerate' === $op ) { if ( ! in_array( $status, array( 'review', 'rejected', 'failed', 'cancelled', 'interrupted' ), true ) ) { return new WP_Error( 'busy', __( 'This product can\'t be regenerated right now.', 'ai-content-generator-for-woocommerce' ) ); } self::discard_draft( $task, $product_id ); // Regenerating resumes a stopped batch. delete_option( self::OPTION_ABORT_PREFIX . $batch_id ); self::queue_product( $batch_id, $task, $product_id, $user_id, self::normalize_options( $task, (array) ( $batch['options'] ?? array() ) ), __( 'Regenerating…', 'ai-content-generator-for-woocommerce' ) ); return true; } if ( 'review' !== $status ) { return new WP_Error( 'not_ready', __( 'This product has nothing waiting for review.', 'ai-content-generator-for-woocommerce' ) ); } if ( 'reject' === $op ) { self::discard_draft( $task, $product_id ); self::record_result( $product_id, $task, $batch_id, 'rejected', __( 'Rejected.', 'ai-content-generator-for-woocommerce' ) ); return true; } $draft = self::get_draft( $task, $product_id ); $product = wc_get_product( $product_id ); if ( ! $draft || $batch_id !== $draft['batch'] || ! $product ) { return new WP_Error( 'missing_draft', __( 'The generated content is no longer available. Regenerate it.', 'ai-content-generator-for-woocommerce' ) ); } $message = 'featured_image' === $task ? self::apply_featured_image( $product, $draft ) : self::apply_description( $product, $draft ); if ( is_wp_error( $message ) ) { return $message; } // The image file was copied into the media library, so only the meta goes. delete_post_meta( $product_id, self::META_DRAFT_PREFIX . $task ); self::record_result( $product_id, $task, $batch_id, 'done', $message ); return true; } /** * Products of a review batch with what the review window shows for them. * Skipped products are left out. * * @param string $batch_id * @param array $batch * @return array[] { product_id, status, message, draft, current } */ public static function get_review_items( $batch_id, array $batch ) { $running = self::is_running( $batch_id ); $stopped = (bool) get_option( self::OPTION_ABORT_PREFIX . $batch_id ); $meta_key = self::META_STATUS_PREFIX . $batch['task']; $items = array(); update_meta_cache( 'post', $batch['ids'] ); foreach ( $batch['ids'] as $product_id ) { $result = get_post_meta( $product_id, $meta_key, true ); $product = wc_get_product( $product_id ); if ( ! $product || ! is_array( $result ) || ( $result['batch'] ?? '' ) !== $batch_id ) { continue; } $status = self::get_display_status( $result, $running, $stopped ); if ( 'skipped' === $status ) { continue; } $draft = 'review' === $status ? self::get_draft( $batch['task'], $product_id ) : null; $items[] = array( 'product_id' => $product_id, 'status' => $status, 'message' => (string) ( $result['message'] ?? '' ), 'time' => (int) ( $result['time'] ?? 0 ), 'draft' => $draft, 'current' => array( 'image_id' => (int) $product->get_image_id(), 'description' => $product->get_description(), 'short_description' => $product->get_short_description(), ), ); } return $items; } // ------------------------------------------------------------------------- // Job // ------------------------------------------------------------------------- /** * Action Scheduler callback: runs one task for one product. * * Runs as the user who started the batch, so capability checks and fix * links match what they could do on the product edit screen. * * @param array $payload { batch, task, product_id, user_id, options, attempt } * @return void */ public static function process( $payload ) { $payload = wp_parse_args( (array) $payload, array( 'batch' => '', 'task' => '', 'product_id' => 0, 'user_id' => 0, 'options' => array(), 'attempt' => 1, ) ); $batch_id = sanitize_key( $payload['batch'] ); $task = sanitize_key( $payload['task'] ); $product_id = absint( $payload['product_id'] ); $options = self::normalize_options( $task, (array) $payload['options'] ); if ( ! $batch_id || ! $product_id || get_option( self::OPTION_ABORT_PREFIX . $batch_id ) ) { return; } if ( function_exists( 'wc_set_time_limit' ) ) { wc_set_time_limit( 300 ); } $previous_user = get_current_user_id(); wp_set_current_user( absint( $payload['user_id'] ) ); try { $result = self::run_task( $task, $product_id, $options, $batch_id ); } catch ( Throwable $e ) { $result = new WP_Error( 'exception', $e->getMessage() ); } if ( is_wp_error( $result ) ) { self::handle_error( $payload, $result ); } else { self::record_result( $product_id, $task, $batch_id, $result['status'], $result['message'] ); } wp_set_current_user( $previous_user ); } /** * Retries, fails, or stops the batch, depending on the error. * * @param array $payload * @param WP_Error $error * @return void */ private static function handle_error( array $payload, WP_Error $error ) { $batch_id = sanitize_key( $payload['batch'] ); $task = sanitize_key( $payload['task'] ); $product_id = absint( $payload['product_id'] ); $attempt = max( 1, (int) $payload['attempt'] ); $data = AI_Content_Generator_For_WooCommerce_Helper::get_error_response_data( $error ); $links = isset( $data['links'] ) ? $data['links'] : array(); AI_Content_Generator_For_WooCommerce_Helper::log_debug( 'Bulk job failed', array( 'batch' => $batch_id, 'task' => $task, 'product_id' => $product_id, 'attempt' => $attempt, 'error' => $error->get_error_message(), ) ); if ( self::is_retryable( $error ) && $attempt < self::MAX_ATTEMPTS ) { $payload['attempt'] = $attempt + 1; as_schedule_single_action( time() + self::RETRY_DELAY * ( 2 ** ( $attempt - 1 ) ), self::HOOK, array( $payload ), self::GROUP_PREFIX . $batch_id ); self::record_result( $product_id, $task, $batch_id, 'queued', sprintf( /* translators: 1: next attempt number, 2: maximum attempts, 3: error message */ __( 'Retrying (attempt %1$d of %2$d): %3$s', 'ai-content-generator-for-woocommerce' ), $attempt + 1, self::MAX_ATTEMPTS, $error->get_error_message() ) ); return; } self::record_result( $product_id, $task, $batch_id, 'failed', $error->get_error_message(), $links ); if ( self::is_fatal( $error ) ) { self::abort( $batch_id, $task, $error->get_error_message(), $links ); } } /** * Errors worth another try: timeouts, rate limits and provider outages. * * @param WP_Error $error * @return bool */ private static function is_retryable( WP_Error $error ) { $explained = self::get_explained( $error ); if ( ! $explained ) { return false; } $code = (int) ( $explained['http_code'] ?? 0 ); if ( 'timeout' === $explained['category'] ) { return true; } if ( 429 === $code ) { // 429 also covers "no billing / out of credit", which retrying won't fix. return ! preg_match( '/insufficient_quota|billing|credit/i', (string) $explained['details'] ); } return $code >= 500 || ( 'unknown' === $explained['category'] && 0 === $code ); } /** * Errors every remaining job in the batch would hit as well. * * @param WP_Error $error * @return bool */ private static function is_fatal( WP_Error $error ) { $fatal_codes = array( 'missing_api_key', 'unsupported_provider_for_images', 'no_seo_plugin', 'review_summary_disabled' ); if ( in_array( $error->get_error_code(), $fatal_codes, true ) ) { return true; } $explained = self::get_explained( $error ); return $explained && in_array( $explained['category'], array( 'invalid_key', 'quota', 'model_unavailable' ), true ); } /** * The explain_provider_error() result attached to a provider error. * * @param WP_Error $error * @return array|null */ private static function get_explained( WP_Error $error ) { $data = $error->get_error_data(); return is_array( $data ) && isset( $data['explained'] ) && is_array( $data['explained'] ) ? $data['explained'] : null; } /** * Runs one task for one product. * * @param string $task * @param int $product_id * @param array $options * @param string $batch_id * @return array{status: string, message: string}|WP_Error */ private static function run_task( $task, $product_id, array $options, $batch_id ) { if ( ! current_user_can( 'edit_product', $product_id ) ) { return new WP_Error( 'forbidden', __( 'You can\'t edit this product.', 'ai-content-generator-for-woocommerce' ) ); } $product = wc_get_product( $product_id ); if ( ! $product ) { return new WP_Error( 'invalid_product', __( 'Invalid product ID.', 'ai-content-generator-for-woocommerce' ) ); } // The product may have changed since the batch was queued. $reason = self::get_skip_reason( $task, $product, $options ); if ( '' !== $reason ) { return array( 'status' => 'skipped', 'message' => $reason ); } switch ( $task ) { case 'featured_image': return self::run_featured_image( $product, $batch_id ); case 'description': return self::run_description( $product, $options, $batch_id ); case 'seo_meta': return self::run_seo_meta( $product, $options ); case 'review_summary': return self::run_review_summary( $product ); } return new WP_Error( 'invalid_task', __( 'Unknown bulk action.', 'ai-content-generator-for-woocommerce' ) ); } /** * Generates an image and keeps it as a draft for review. * * @param WC_Product $product * @param string $batch_id * @return array|WP_Error */ private static function run_featured_image( $product, $batch_id ) { $available = AI_Content_Generator_For_WooCommerce_Helper::can_generate_images(); if ( is_wp_error( $available ) ) { return $available; } $result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_images( $product->get_id() ); if ( is_wp_error( $result ) ) { return $result; } $image_urls = isset( $result['image_urls'] ) ? (array) $result['image_urls'] : array(); if ( empty( $image_urls ) ) { return new WP_Error( 'no_images', __( 'No images were generated.', 'ai-content-generator-for-woocommerce' ) ); } $image_url = AI_Content_Generator_For_WooCommerce_Helper::keep_generated_image( $image_urls[0] ); AI_Content_Generator_For_WooCommerce_Helper::discard_generated_images( array_slice( $image_urls, 1 ) ); if ( is_wp_error( $image_url ) ) { return $image_url; } self::save_draft( 'featured_image', $product->get_id(), $batch_id, array( 'image_url' => $image_url ) ); return array( 'status' => 'review', 'message' => __( 'Ready for review.', 'ai-content-generator-for-woocommerce' ) ); } /** * Writes the description fields and keeps them as a draft for review. * * @param WC_Product $product * @param array $options * @param string $batch_id * @return array|WP_Error */ private static function run_description( $product, array $options, $batch_id ) { $product_id = $product->get_id(); $fields = self::get_description_fields_to_write( $product, $options ); $values = array(); if ( in_array( 'description', $fields, true ) ) { // One call returns both the description and an excerpt. $result = AI_Content_Generator_For_WooCommerce_Helper::api_generate_description( $product_id, $options['tone'] ); if ( is_wp_error( $result ) ) { return $result; } if ( '' === trim( wp_strip_all_tags( $result['description'] ) ) ) { return new WP_Error( 'empty_description', __( 'The AI returned an empty description.', 'ai-content-generator-for-woocommerce' ) ); } $values['description'] = $result['description']; if ( '' !== trim( $result['excerpt'] ) ) { $values['short_description'] = wpautop( $result['excerpt'] ); } } if ( in_array( 'short_description', $fields, true ) && ! isset( $values['short_description'] ) ) { $short = AI_Content_Generator_For_WooCommerce_Helper::api_generate_short_description( $product_id, $options['tone'] ); if ( is_wp_error( $short ) ) { return $short; } $values['short_description'] = $short; } self::save_draft( 'description', $product_id, $batch_id, array( 'values' => array_intersect_key( $values, array_flip( $fields ) ), ) ); return array( 'status' => 'review', 'message' => __( 'Ready for review.', 'ai-content-generator-for-woocommerce' ) ); } /** * Sets an approved image as the featured image. * * @param WC_Product $product * @param array $draft * @return string|WP_Error Result message. */ private static function apply_featured_image( $product, array $draft ) { $previous_image = (int) $product->get_image_id(); $attach_id = AI_Content_Generator_For_WooCommerce_Helper::attach_image_to_product( $product->get_id(), (string) $draft['image_url'] ); if ( is_wp_error( $attach_id ) ) { return $attach_id; } AI_Content_Generator_For_WooCommerce_Helper::discard_generated_images( array( $draft['image_url'] ) ); self::backup( $product->get_id(), array( 'image_id' => $previous_image ) ); return __( 'Featured image added.', 'ai-content-generator-for-woocommerce' ); } /** * Writes approved description fields to the product. * * @param WC_Product $product * @param array $draft * @return string|WP_Error Result message. */ private static function apply_description( $product, array $draft ) { $values = array_intersect_key( (array) ( $draft['values'] ?? array() ), array_flip( array( 'description', 'short_description' ) ) ); if ( ! $values ) { return new WP_Error( 'missing_draft', __( 'The generated content is no longer available. Regenerate it.', 'ai-content-generator-for-woocommerce' ) ); } self::backup( $product->get_id(), array_intersect_key( array( 'description' => $product->get_description(), 'short_description' => $product->get_short_description(), ), $values ) ); if ( isset( $values['description'] ) ) { $product->set_description( wp_kses_post( $values['description'] ) ); } if ( isset( $values['short_description'] ) ) { $product->set_short_description( wp_kses_post( $values['short_description'] ) ); } $product->save(); update_post_meta( $product->get_id(), '_wtofe_ai_generated', '1' ); if ( 2 === count( $values ) ) { return __( 'Description and short description written.', 'ai-content-generator-for-woocommerce' ); } return isset( $values['description'] ) ? __( 'Description written.', 'ai-content-generator-for-woocommerce' ) : __( 'Short description written.', 'ai-content-generator-for-woocommerce' ); } /** * @param WC_Product $product * @param array $options * @return array|WP_Error */ private static function run_seo_meta( $product, array $options ) { $provider = WTOFE_SEO_Meta_Provider_Registry::get_active_provider(); if ( ! $provider ) { return new WP_Error( 'no_seo_plugin', __( 'No supported SEO plugin is active.', 'ai-content-generator-for-woocommerce' ) ); } $product_id = $product->get_id(); $result = WTOFE_SEO_Meta_Generator::generate( $product_id ); if ( is_wp_error( $result ) ) { return $result; } $old_title = $provider->get_meta_title( $product_id ); $old_description = $provider->get_meta_description( $product_id ); $backup = array(); if ( $options['overwrite'] || '' === trim( $old_title ) ) { $backup['seo_title'] = $old_title; $provider->save_meta_title( $product_id, $result['title'] ); } if ( $options['overwrite'] || '' === trim( $old_description ) ) { $backup['seo_description'] = $old_description; $provider->save_meta_description( $product_id, $result['description'] ); } self::backup( $product_id, $backup ); update_post_meta( $product_id, '_wtofe_ai_generated', '1' ); return array( 'status' => 'done', 'message' => __( 'SEO meta written.', 'ai-content-generator-for-woocommerce' ) ); } /** * @param WC_Product $product * @return array|WP_Error */ private static function run_review_summary( $product ) { $result = WTOFE_Review_Summary_Generator::generate( $product->get_id() ); // Short or duplicate reviews are filtered out, so a product can pass // the approved-count check and still come up short here. if ( is_wp_error( $result ) && 'not_enough_reviews' === $result->get_error_code() ) { return array( 'status' => 'skipped', 'message' => $result->get_error_message() ); } if ( is_wp_error( $result ) ) { return $result; } return array( 'status' => 'done', 'message' => __( 'Review summary updated.', 'ai-content-generator-for-woocommerce' ) ); } // ------------------------------------------------------------------------- // Backup & restore // ------------------------------------------------------------------------- /** * Saves the values bulk generation is about to replace. A field already * in the backup keeps its older value, so restoring always goes back to * the content from before the first bulk run. * * @param int $product_id * @param array $values Field => previous value. * @return void */ private static function backup( $product_id, array $values ) { if ( empty( $values ) ) { return; } $backup = get_post_meta( $product_id, self::META_BACKUP, true ); $backup = is_array( $backup ) ? $backup : array(); update_post_meta( $product_id, self::META_BACKUP, $backup + $values ); } /** * Whether a product has content saved from before a bulk run. * * @param int $product_id * @return bool */ public static function has_backup( $product_id ) { $backup = get_post_meta( $product_id, self::META_BACKUP, true ); return is_array( $backup ) && ! empty( $backup ); } /** * Puts back the content bulk generation replaced and clears the backup. * SEO fields stay in the backup while no SEO plugin is active. * * @param int $product_id * @return bool True when anything was restored. */ public static function restore_backup( $product_id ) { $backup = get_post_meta( $product_id, self::META_BACKUP, true ); $product = wc_get_product( $product_id ); if ( ! is_array( $backup ) || empty( $backup ) || ! $product ) { return false; } $restored = false; if ( array_key_exists( 'description', $backup ) ) { $product->set_description( $backup['description'] ); unset( $backup['description'] ); $restored = true; } if ( array_key_exists( 'short_description', $backup ) ) { $product->set_short_description( $backup['short_description'] ); unset( $backup['short_description'] ); $restored = true; } if ( array_key_exists( 'image_id', $backup ) ) { $product->set_image_id( (int) $backup['image_id'] ); unset( $backup['image_id'] ); $restored = true; } if ( $restored ) { $product->save(); } $provider = WTOFE_SEO_Meta_Provider_Registry::get_active_provider(); if ( $provider ) { if ( array_key_exists( 'seo_title', $backup ) ) { $provider->save_meta_title( $product_id, $backup['seo_title'] ); unset( $backup['seo_title'] ); $restored = true; } if ( array_key_exists( 'seo_description', $backup ) ) { $provider->save_meta_description( $product_id, $backup['seo_description'] ); unset( $backup['seo_description'] ); $restored = true; } } if ( empty( $backup ) ) { delete_post_meta( $product_id, self::META_BACKUP ); } else { update_post_meta( $product_id, self::META_BACKUP, $backup ); } return $restored; } }