id; } // ------------------------------------------------------------------------- // Bulk actions // ------------------------------------------------------------------------- /** * Labels for the dropdown and the confirm dialog title, keyed by bulk action. * * @return array */ private static function get_action_labels() { return array( self::ACTION_PREFIX . 'featured_image' => __( 'Generate featured images', 'ai-content-generator-for-woocommerce' ), self::ACTION_PREFIX . 'description' => __( 'Generate descriptions', 'ai-content-generator-for-woocommerce' ), self::ACTION_PREFIX . 'seo_meta' => __( 'Generate SEO meta', 'ai-content-generator-for-woocommerce' ), self::ACTION_PREFIX . 'review_summary' => __( 'Regenerate review summaries', 'ai-content-generator-for-woocommerce' ), self::ACTION_PREFIX . 'restore' => __( 'Restore content from before AI', 'ai-content-generator-for-woocommerce' ), self::ACTION_PREFIX . 'mark_ai' => __( 'Mark as AI-generated', 'ai-content-generator-for-woocommerce' ), self::ACTION_PREFIX . 'unmark_ai' => __( 'Unmark as AI-generated', 'ai-content-generator-for-woocommerce' ), ); } /** * Adds the "AI Content Generator" optgroup to the Bulk actions dropdown. * * @param array $actions * @return array */ public static function register_bulk_actions( $actions ) { if ( ! current_user_can( 'edit_products' ) ) { return $actions; } $group = array(); foreach ( self::get_action_labels() as $action => $label ) { $key = substr( $action, strlen( self::ACTION_PREFIX ) ); if ( in_array( $key, self::SYNC_ACTIONS, true ) || true === WTOFE_Bulk_Actions_Runner::is_task_available( $key ) ) { $group[ $action ] = $label; } } $actions[ __( 'AI Content Generator', 'ai-content-generator-for-woocommerce' ) ] = $group; return $actions; } /** * Runs one of this module's bulk actions. Core has already checked the * bulk-posts nonce by the time this filter runs. * * @param string $redirect * @param string $action * @param int[] $post_ids * @return string Redirect URL. */ public static function handle_bulk_action( $redirect, $action, $post_ids ) { if ( 0 !== strpos( (string) $action, self::ACTION_PREFIX ) || ! current_user_can( 'edit_products' ) ) { return $redirect; } $key = substr( $action, strlen( self::ACTION_PREFIX ) ); $redirect = remove_query_arg( array( 'wtofe_done', 'wtofe_count', 'wtofe_error' ), $redirect ); if ( in_array( $key, self::SYNC_ACTIONS, true ) ) { $count = self::run_sync_action( $key, $post_ids ); return add_query_arg( array( 'wtofe_done' => $key, 'wtofe_count' => $count ), $redirect ); } $tasks = WTOFE_Bulk_Actions_Runner::get_tasks(); if ( ! isset( $tasks[ $key ] ) ) { return $redirect; } $options = WTOFE_Bulk_Actions_Runner::normalize_options( $key, self::get_request_options() ); $batch = WTOFE_Bulk_Actions_Runner::start_batch( $key, (array) $post_ids, $options ); if ( is_wp_error( $batch ) ) { set_transient( 'wtofe_bulk_error_' . get_current_user_id(), $batch->get_error_message(), MINUTE_IN_SECONDS ); return add_query_arg( 'wtofe_error', 1, $redirect ); } return $redirect; } /** * Options from the confirm dialog, sent as extra fields with the bulk form. * * @return array */ private static function get_request_options() { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- core verified the bulk-posts nonce before handle_bulk_actions-edit-product. return array( 'overwrite' => ! empty( $_REQUEST['wtofe_overwrite'] ), 'force' => ! empty( $_REQUEST['wtofe_force'] ), 'tone' => isset( $_REQUEST['wtofe_tone'] ) ? sanitize_key( wp_unslash( $_REQUEST['wtofe_tone'] ) ) : '', 'fields' => isset( $_REQUEST['wtofe_fields'] ) ? array_map( 'sanitize_key', (array) wp_unslash( $_REQUEST['wtofe_fields'] ) ) : array(), ); // phpcs:enable WordPress.Security.NonceVerification.Recommended } /** * Marks, unmarks or restores products right away. * * @param string $key restore, mark_ai or unmark_ai. * @param int[] $post_ids * @return int Products changed. */ private static function run_sync_action( $key, $post_ids ) { $count = 0; foreach ( array_map( 'absint', (array) $post_ids ) as $post_id ) { if ( 'product' !== get_post_type( $post_id ) || ! current_user_can( 'edit_product', $post_id ) ) { continue; } if ( 'mark_ai' === $key ) { update_post_meta( $post_id, '_wtofe_ai_generated', '1' ); ++$count; } elseif ( 'unmark_ai' === $key ) { delete_post_meta( $post_id, '_wtofe_ai_generated' ); ++$count; } elseif ( WTOFE_Bulk_Actions_Runner::restore_backup( $post_id ) ) { ++$count; } } return $count; } /** * Keeps this module's result flags out of the address bar after load. * * @param string[] $args * @return string[] */ public static function removable_query_args( $args ) { return array_merge( $args, array( 'wtofe_done', 'wtofe_count', 'wtofe_error' ) ); } // ------------------------------------------------------------------------- // Row action & "Missing content" filter // ------------------------------------------------------------------------- /** * Adds "Generate image" under each product name. Without JavaScript the * link runs the bulk action for that product with the default options. * * @param string[] $actions * @param WP_Post $post * @return string[] */ public static function add_row_action( $actions, $post ) { if ( 'product' !== $post->post_type || 'trash' === $post->post_status || ! current_user_can( 'edit_product', $post->ID ) || true !== WTOFE_Bulk_Actions_Runner::is_task_available( 'featured_image' ) ) { return $actions; } $url = wp_nonce_url( add_query_arg( array( 'post_type' => 'product', 'action' => self::ACTION_PREFIX . 'featured_image', 'post[]' => $post->ID, ), admin_url( 'edit.php' ) ), 'bulk-posts' ); $actions['wtofe_generate_image'] = sprintf( '%s', esc_url( $url ), esc_attr( self::ACTION_PREFIX . 'featured_image' ), (int) $post->ID, /* translators: %s: product name */ esc_attr( sprintf( __( 'Generate a featured image for “%s” with AI', 'ai-content-generator-for-woocommerce' ), get_the_title( $post ) ) ), esc_html__( 'Generate image', 'ai-content-generator-for-woocommerce' ) ); return $actions; } /** * Renders the "Missing content" filter next to WooCommerce's own filters. * * @param string $post_type * @param string $which top or bottom. * @return void */ public static function render_missing_filter( $post_type, $which = 'top' ) { if ( 'product' !== $post_type || 'top' !== $which ) { return; } $current = self::get_missing_filter(); $options = array( '' => __( 'Filter by missing content', 'ai-content-generator-for-woocommerce' ), 'image' => __( 'Missing featured image', 'ai-content-generator-for-woocommerce' ), 'description' => __( 'Missing description', 'ai-content-generator-for-woocommerce' ), ); ?> is_main_query() || 'product' !== $query->get( 'post_type' ) ) { return; } $missing = self::get_missing_filter(); if ( 'image' === $missing ) { $meta_query = (array) $query->get( 'meta_query' ); $meta_query[] = array( 'relation' => 'OR', array( 'key' => '_thumbnail_id', 'compare' => 'NOT EXISTS' ), array( 'key' => '_thumbnail_id', 'value' => array( '', '0' ), 'compare' => 'IN' ), ); $query->set( 'meta_query', $meta_query ); } elseif ( 'description' === $missing ) { $query->set( 'wtofe_missing_description', true ); } } /** * SQL for the "Missing description" filter. * * @param string $where * @param WP_Query $query * @return string */ public static function where_missing_description( $where, $query ) { global $wpdb; if ( $query->get( 'wtofe_missing_description' ) ) { $where .= " AND TRIM( {$wpdb->posts}.post_content ) = ''"; } return $where; } // ------------------------------------------------------------------------- // Notices // ------------------------------------------------------------------------- /** * Shows results of instant actions, start errors, and one progress * notice per batch the current user started. * * @return void */ public static function render_notices() { if ( ! self::is_products_screen() || ! current_user_can( 'edit_products' ) ) { return; } // phpcs:disable WordPress.Security.NonceVerification.Recommended -- read-only result flags set by handle_bulk_action(). if ( isset( $_GET['wtofe_done'] ) ) { $done = sanitize_key( wp_unslash( $_GET['wtofe_done'] ) ); $count = isset( $_GET['wtofe_count'] ) ? absint( $_GET['wtofe_count'] ) : 0; self::render_sync_notice( $done, $count ); } // phpcs:enable WordPress.Security.NonceVerification.Recommended $error = get_transient( 'wtofe_bulk_error_' . get_current_user_id() ); if ( $error ) { delete_transient( 'wtofe_bulk_error_' . get_current_user_id() ); printf( '

%s %s

', esc_html__( 'AI Content Generator:', 'ai-content-generator-for-woocommerce' ), esc_html( $error ) ); } foreach ( WTOFE_Bulk_Actions_Runner::get_user_batches( get_current_user_id() ) as $batch_id => $batch ) { echo self::render_batch_notice( $batch_id, $batch )['html']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped while building. } } /** * @param string $done restore, mark_ai or unmark_ai. * @param int $count * @return void */ private static function render_sync_notice( $done, $count ) { switch ( $done ) { case 'mark_ai': /* translators: %d: number of products */ $message = sprintf( _n( '%d product marked as AI-generated.', '%d products marked as AI-generated.', $count, 'ai-content-generator-for-woocommerce' ), $count ); break; case 'unmark_ai': /* translators: %d: number of products */ $message = sprintf( _n( 'AI-generated mark removed from %d product.', 'AI-generated mark removed from %d products.', $count, 'ai-content-generator-for-woocommerce' ), $count ); break; case 'restore': $message = $count /* translators: %d: number of products */ ? sprintf( _n( 'Restored the content from before AI on %d product.', 'Restored the content from before AI on %d products.', $count, 'ai-content-generator-for-woocommerce' ), $count ) : __( 'None of the selected products had content saved from before a bulk AI run.', 'ai-content-generator-for-woocommerce' ); break; default: return; } printf( '

%s

', $count ? 'notice-success' : 'notice-warning', esc_html( $message ) ); } /** * Progress notice for one batch. Used on page load, by the polling AJAX * call and by Cancel, so all three render the same markup. * * A settled batch (no jobs left, nothing waiting for review) is shown * once: it is forgotten as soon as its final state has been rendered, so * the notice is gone on the next page load. * * @param string $batch_id * @param array $batch * @return array{html: string, running: bool, settled: bool} */ private static function render_batch_notice( $batch_id, array $batch ) { $progress = WTOFE_Bulk_Actions_Runner::get_progress( $batch_id, $batch ); if ( $progress['settled'] ) { WTOFE_Bulk_Actions_Runner::dismiss_batch( get_current_user_id(), $batch_id ); } return array( 'html' => self::get_batch_notice_html( $batch_id, $progress ), 'running' => $progress['running'], 'settled' => $progress['settled'], ); } /** * @param string $batch_id * @param array $progress From WTOFE_Bulk_Actions_Runner::get_progress(). * @return string */ private static function get_batch_notice_html( $batch_id, array $progress ) { $tasks = WTOFE_Bulk_Actions_Runner::get_tasks(); $label = $tasks[ $progress['task'] ]['label']; $processed = $progress['total'] - $progress['pending']; if ( $progress['running'] ) { $class = 'notice-info'; /* translators: 1: task name, e.g. Featured images, 2: products processed, 3: products selected */ $headline = sprintf( __( '%1$s: %2$d of %3$d processed…', 'ai-content-generator-for-woocommerce' ), $label, $processed, $progress['total'] ); } elseif ( $progress['stopped'] ) { $class = 'notice-error'; /* translators: %s: task name, e.g. Featured images */ $headline = sprintf( __( '%s: stopped.', 'ai-content-generator-for-woocommerce' ), $label ); } elseif ( $progress['review'] ) { $class = 'notice-info'; /* translators: %s: task name, e.g. Featured images */ $headline = sprintf( __( '%s: ready for review.', 'ai-content-generator-for-woocommerce' ), $label ); } else { $class = $progress['failed'] ? 'notice-warning' : 'notice-success'; /* translators: %s: task name, e.g. Featured images */ $headline = sprintf( __( '%s: finished.', 'ai-content-generator-for-woocommerce' ), $label ); } $counts = array(); if ( $progress['review'] ) { /* translators: %d: number of products */ $counts[] = sprintf( _n( '%d to review', '%d to review', $progress['review'], 'ai-content-generator-for-woocommerce' ), $progress['review'] ); } if ( $progress['done'] ) { $counts[] = $progress['review_task'] /* translators: %d: number of products */ ? sprintf( _n( '%d approved', '%d approved', $progress['done'], 'ai-content-generator-for-woocommerce' ), $progress['done'] ) /* translators: %d: number of products */ : sprintf( _n( '%d updated', '%d updated', $progress['done'], 'ai-content-generator-for-woocommerce' ), $progress['done'] ); } if ( $progress['rejected'] ) { /* translators: %d: number of products */ $counts[] = sprintf( _n( '%d rejected', '%d rejected', $progress['rejected'], 'ai-content-generator-for-woocommerce' ), $progress['rejected'] ); } if ( $progress['skipped'] ) { /* translators: %d: number of products */ $counts[] = sprintf( _n( '%d skipped', '%d skipped', $progress['skipped'], 'ai-content-generator-for-woocommerce' ), $progress['skipped'] ); } if ( $progress['failed'] ) { /* translators: %d: number of products */ $counts[] = sprintf( _n( '%d failed', '%d failed', $progress['failed'], 'ai-content-generator-for-woocommerce' ), $progress['failed'] ); } if ( $progress['cancelled'] ) { /* translators: %d: number of products */ $counts[] = sprintf( _n( '%d not processed', '%d not processed', $progress['cancelled'], 'ai-content-generator-for-woocommerce' ), $progress['cancelled'] ); } ob_start(); ?>

—

  • :
  • self::MAX_LISTED_FAILURES ) : ?>
    $count ) : ?>
' . esc_html( $title ) . '' : esc_html( $title ); } /** * Fix links from get_error_response_data(), joined with dots. * * @param array[] $links * @return string */ private static function get_links_html( array $links ) { $html = array(); foreach ( $links as $link ) { if ( empty( $link['url'] ) || empty( $link['label'] ) ) { continue; } $html[] = sprintf( '%s', esc_url( $link['url'] ), empty( $link['external'] ) ? '' : ' target="_blank" rel="noopener noreferrer"', esc_html( $link['label'] ) ); } return $html ? '' . implode( ' · ', $html ) . '' : ''; } // ------------------------------------------------------------------------- // Review window // ------------------------------------------------------------------------- /** * Title of the review window for a task. * * @param string $task * @return string */ private static function get_review_title( $task ) { return 'featured_image' === $task ? __( 'Review featured images', 'ai-content-generator-for-woocommerce' ) : __( 'Review descriptions', 'ai-content-generator-for-woocommerce' ); } /** * Everything the review window shows for a batch, plus the refreshed * progress notice. * * @param string $batch_id * @param array $batch * @return array */ private static function get_review_payload( $batch_id, array $batch ) { $items = WTOFE_Bulk_Actions_Runner::get_review_items( $batch_id, $batch ); $notice = self::render_batch_notice( $batch_id, $batch ); $counts = array( 'review' => 0, 'generating' => 0, 'done' => 0, 'rejected' => 0 ); $cards = array(); foreach ( $items as $item ) { if ( isset( $counts[ $item['status'] ] ) ) { ++$counts[ $item['status'] ]; } } foreach ( $items as $item ) { $cards[] = array( 'id' => $item['product_id'], 'state' => $item['status'] . '-' . $item['time'] . ( $notice['settled'] ? '-settled' : '' ), 'html' => self::get_review_card_html( $batch['task'], $item, $notice['settled'] ), ); } $summary = array(); if ( $counts['review'] ) { /* translators: %d: number of products */ $summary[] = sprintf( _n( '%d ready for review', '%d ready for review', $counts['review'], 'ai-content-generator-for-woocommerce' ), $counts['review'] ); } if ( $counts['generating'] ) { /* translators: %d: number of products */ $summary[] = sprintf( _n( '%d generating', '%d generating', $counts['generating'], 'ai-content-generator-for-woocommerce' ), $counts['generating'] ); } if ( $counts['done'] ) { /* translators: %d: number of products */ $summary[] = sprintf( _n( '%d approved', '%d approved', $counts['done'], 'ai-content-generator-for-woocommerce' ), $counts['done'] ); } if ( $counts['rejected'] ) { /* translators: %d: number of products */ $summary[] = sprintf( _n( '%d rejected', '%d rejected', $counts['rejected'], 'ai-content-generator-for-woocommerce' ), $counts['rejected'] ); } $summary = implode( ' · ', $summary ); if ( ! $counts['review'] && ! $counts['generating'] ) { $summary = '' === $summary ? __( 'All results reviewed.', 'ai-content-generator-for-woocommerce' ) /* translators: %s: counts, e.g. "3 approved · 1 rejected" */ : sprintf( __( 'All results reviewed: %s', 'ai-content-generator-for-woocommerce' ), $summary ); } return array( 'cards' => $cards, 'summary' => $summary, 'review' => $counts['review'], 'generating' => $counts['generating'], 'settled' => $notice['settled'], 'notice' => $notice, ); } /** * One product card in the review window. * * @param string $task * @param array $item From WTOFE_Bulk_Actions_Runner::get_review_items(). * @param bool $settled True once the batch is over; actions are hidden. * @return string */ private static function get_review_card_html( $task, array $item, $settled ) { ob_start(); require WTOFE_AI_PLUGIN_DIR . 'admin/modules/bulk-actions/partials/review-card.php'; return (string) ob_get_clean(); } // ------------------------------------------------------------------------- // Confirm dialog & assets // ------------------------------------------------------------------------- /** * Enqueues the dialog and polling script on the Products list. * * @param string $hook * @return void */ public static function enqueue_scripts( $hook ) { if ( 'edit.php' !== $hook || ! self::is_products_screen() || ! current_user_can( 'edit_products' ) ) { return; } wp_enqueue_style( 'wtofe-bulk-actions', WTOFE_AI_PLUGIN_URL . 'admin/modules/bulk-actions/assets/css/bulk-actions.css', array(), WTOFE_AI_VERSION ); wp_enqueue_script( 'wtofe-bulk-actions', WTOFE_AI_PLUGIN_URL . 'admin/modules/bulk-actions/assets/js/bulk-actions.js', array( 'jquery' ), WTOFE_AI_VERSION, true ); $dialog_actions = array(); foreach ( self::get_action_labels() as $action => $label ) { $key = substr( $action, strlen( self::ACTION_PREFIX ) ); if ( in_array( $key, array( 'mark_ai', 'unmark_ai' ), true ) ) { continue; } $dialog_actions[ $action ] = array( 'key' => $key, 'title' => $label ); } wp_localize_script( 'wtofe-bulk-actions', 'wtofeBulk', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( self::NONCE ), 'actions' => $dialog_actions, 'pollInterval' => 4000, 'i18n' => array( 'checking' => __( 'Checking the selected products…', 'ai-content-generator-for-woocommerce' ), /* translators: %d: number of products */ 'selectedOne' => __( '%d product selected.', 'ai-content-generator-for-woocommerce' ), /* translators: %d: number of products */ 'selectedMany' => __( '%d products selected.', 'ai-content-generator-for-woocommerce' ), /* translators: 1: number of products, 2: reason */ 'skipped' => __( '%1$d skipped: %2$s', 'ai-content-generator-for-woocommerce' ), /* translators: 1: products per run, 2: number of products left out */ 'overLimit' => __( 'Only %1$d products are processed per run, so %2$d will be left out. Run it again for those.', 'ai-content-generator-for-woocommerce' ), /* translators: %s: one or more "N requests to Provider (model)" parts, comma-separated */ 'cost' => __( 'This sends %s.', 'ai-content-generator-for-woocommerce' ), /* translators: 1: number of requests, 2: provider and model, e.g. OpenAI (gpt-image-2) */ 'costOne' => __( '%1$d request to %2$s', 'ai-content-generator-for-woocommerce' ), /* translators: 1: number of requests, 2: provider and model, e.g. OpenAI (gpt-image-2) */ 'costMany' => __( '%1$d requests to %2$s', 'ai-content-generator-for-woocommerce' ), /* translators: %d: number of products */ 'restoreOne' => __( '%d product will be restored.', 'ai-content-generator-for-woocommerce' ), /* translators: %d: number of products */ 'restoreMany' => __( '%d products will be restored.', 'ai-content-generator-for-woocommerce' ), 'nothingToDo' => __( 'There is nothing to do for the selected products.', 'ai-content-generator-for-woocommerce' ), 'noFields' => __( 'Choose at least one field to write.', 'ai-content-generator-for-woocommerce' ), 'start' => __( 'Start', 'ai-content-generator-for-woocommerce' ), 'restore' => __( 'Restore', 'ai-content-generator-for-woocommerce' ), 'error' => __( 'Could not check the selected products. Reload the page and try again.', 'ai-content-generator-for-woocommerce' ), 'reload' => __( 'Reload the list to see the changes', 'ai-content-generator-for-woocommerce' ), 'loading' => __( 'Loading results…', 'ai-content-generator-for-woocommerce' ), 'reviewError' => __( 'Something went wrong. Try again.', 'ai-content-generator-for-woocommerce' ), 'rejectAll' => __( 'Reject every result waiting for review? The generated content is thrown away.', 'ai-content-generator-for-woocommerce' ), ), ) ); } /** * Prints the confirm dialog in the Products list footer. * * @return void */ public static function render_modal() { if ( ! self::is_products_screen() || ! current_user_can( 'edit_products' ) ) { return; } $tones = array( 'formal' => __( 'Formal & Professional', 'ai-content-generator-for-woocommerce' ), 'casual' => __( 'Casual & Friendly', 'ai-content-generator-for-woocommerce' ), 'persuasive' => __( 'Persuasive & Sales-focused', 'ai-content-generator-for-woocommerce' ), 'technical' => __( 'Technical & Detailed', 'ai-content-generator-for-woocommerce' ), 'luxury' => __( 'Luxury & Premium', 'ai-content-generator-for-woocommerce' ), 'creative' => __( 'Creative & Engaging', 'ai-content-generator-for-woocommerce' ), ); require WTOFE_AI_PLUGIN_DIR . 'admin/modules/bulk-actions/partials/bulk-modal.php'; require WTOFE_AI_PLUGIN_DIR . 'admin/modules/bulk-actions/partials/review-modal.php'; } // ------------------------------------------------------------------------- // AJAX // ------------------------------------------------------------------------- /** * Counts what a bulk action would do with the dialog's current options. * Nothing is changed. */ public static function ajax_preflight() { self::verify_request(); // phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified above in self::verify_request(). $action = isset( $_POST['bulk_action'] ) ? sanitize_key( wp_unslash( $_POST['bulk_action'] ) ) : ''; $ids = isset( $_POST['ids'] ) ? array_map( 'absint', (array) wp_unslash( $_POST['ids'] ) ) : array(); $raw = isset( $_POST['options'] ) && is_array( $_POST['options'] ) ? wp_unslash( $_POST['options'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- sanitised in normalize_options(). // phpcs:enable WordPress.Security.NonceVerification.Missing $key = substr( $action, strlen( self::ACTION_PREFIX ) ); if ( 'restore' === $key ) { $count = 0; foreach ( $ids as $id ) { if ( current_user_can( 'edit_product', $id ) && WTOFE_Bulk_Actions_Runner::has_backup( $id ) ) { ++$count; } } wp_send_json_success( array( 'total' => count( $ids ), 'process' => $count ) ); } $available = WTOFE_Bulk_Actions_Runner::is_task_available( $key ); if ( is_wp_error( $available ) ) { wp_send_json_error( array( 'message' => $available->get_error_message() ) ); } $options = WTOFE_Bulk_Actions_Runner::normalize_options( $key, $raw ); $plan = WTOFE_Bulk_Actions_Runner::plan( $key, $ids, $options ); $reasons = array(); foreach ( array_count_values( $plan['skipped'] ) as $reason => $count ) { $reasons[] = array( 'reason' => $reason, 'count' => $count ); } wp_send_json_success( array( 'total' => count( $ids ), 'process' => count( $plan['process'] ), 'over_limit' => count( $plan['over_limit'] ), 'limit' => WTOFE_Bulk_Actions_Runner::get_max_products( $key ), 'skipped' => $reasons, 'requests' => WTOFE_Bulk_Actions_Runner::count_requests( $key, $plan['process'], $options ), ) ); } /** * Returns fresh notice markup for the given batches. */ public static function ajax_progress() { self::verify_request(); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified above in self::verify_request(). $requested = isset( $_POST['batches'] ) ? array_map( 'sanitize_key', (array) wp_unslash( $_POST['batches'] ) ) : array(); $batches = WTOFE_Bulk_Actions_Runner::get_user_batches( get_current_user_id() ); $response = array(); foreach ( $requested as $batch_id ) { $response[ $batch_id ] = isset( $batches[ $batch_id ] ) ? self::render_batch_notice( $batch_id, $batches[ $batch_id ] ) : null; } wp_send_json_success( array( 'batches' => $response ) ); } /** * Stops one of the user's running batches. */ public static function ajax_cancel() { self::verify_request(); $batch_id = self::get_posted_batch(); $batches = WTOFE_Bulk_Actions_Runner::get_user_batches( get_current_user_id() ); if ( ! isset( $batches[ $batch_id ] ) || ! WTOFE_Bulk_Actions_Runner::cancel_batch( get_current_user_id(), $batch_id ) ) { wp_send_json_error( array( 'message' => __( 'This bulk action no longer exists.', 'ai-content-generator-for-woocommerce' ) ) ); } wp_send_json_success( self::render_batch_notice( $batch_id, $batches[ $batch_id ] ) ); } /** * Loads the review window for one of the user's batches. */ public static function ajax_review() { self::verify_request(); $batch_id = self::get_posted_batch(); $batches = WTOFE_Bulk_Actions_Runner::get_user_batches( get_current_user_id() ); if ( ! isset( $batches[ $batch_id ] ) || ! WTOFE_Bulk_Actions_Runner::needs_review( $batches[ $batch_id ]['task'] ) ) { wp_send_json_error( array( 'message' => __( 'This bulk action no longer exists.', 'ai-content-generator-for-woocommerce' ) ) ); } wp_send_json_success( self::get_review_payload( $batch_id, $batches[ $batch_id ] ) ); } /** * Approves, rejects or regenerates one product's result, or approves or * rejects every result waiting for review when no product is given. */ public static function ajax_review_action() { self::verify_request(); $batch_id = self::get_posted_batch(); // phpcs:disable WordPress.Security.NonceVerification.Missing -- nonce verified above in self::verify_request(). $op = isset( $_POST['op'] ) ? sanitize_key( wp_unslash( $_POST['op'] ) ) : ''; $product_id = isset( $_POST['product_id'] ) ? absint( $_POST['product_id'] ) : 0; // phpcs:enable WordPress.Security.NonceVerification.Missing $batches = WTOFE_Bulk_Actions_Runner::get_user_batches( get_current_user_id() ); if ( ! isset( $batches[ $batch_id ] ) ) { wp_send_json_error( array( 'message' => __( 'This bulk action no longer exists.', 'ai-content-generator-for-woocommerce' ) ) ); } $result = WTOFE_Bulk_Actions_Runner::review( get_current_user_id(), $batch_id, $op, $product_id ? array( $product_id ) : array() ); if ( is_wp_error( $result ) ) { wp_send_json_error( array( 'message' => $result->get_error_message(), 'product_id' => $product_id ) ); } wp_send_json_success( self::get_review_payload( $batch_id, $batches[ $batch_id ] ) ); } /** * @return string */ private static function get_posted_batch() { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in self::verify_request() by every caller. return isset( $_POST['batch'] ) ? sanitize_key( wp_unslash( $_POST['batch'] ) ) : ''; } /** * Shared nonce + capability check for the AJAX handlers. */ private static function verify_request() { if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), self::NONCE ) ) { wp_send_json_error( array( 'message' => __( 'Invalid nonce.', 'ai-content-generator-for-woocommerce' ) ) ); } if ( ! current_user_can( 'edit_products' ) ) { wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', 'ai-content-generator-for-woocommerce' ) ) ); } } }