posts = $posts; } public function register(): void { add_action( self::ACTION, array( $this, 'run_task' ), 10, 3 ); add_action( self::AUTO_ACTION, array( $this, 'run_auto' ), 10, 2 ); } private static function table(): string { global $wpdb; return $wpdb->prefix . 'tp_jobs'; } private static function group( int $job_id ): string { return self::GROUP . '-job-' . $job_id; } /** * Resolve which (post, language) pairs a job covers. * * @param array $spec post_types[], languages[], mode missing|update|all, ids[]. * @return array */ public static function tasks( array $spec ): array { global $wpdb; $types = array_values( array_intersect( (array) ( $spec['post_types'] ?? PostTypes::enabled() ), PostTypes::enabled() ) ); $langs = array_values( array_intersect( (array) ( $spec['languages'] ?? Languages::targets() ), Languages::targets() ) ); $mode = in_array( $spec['mode'] ?? 'missing', array( 'missing', 'update', 'all' ), true ) ? $spec['mode'] : 'missing'; if ( ! $types || ! $langs ) { return array(); } $statuses = array( 'publish', 'future', 'private' ); if ( ! empty( $spec['include_drafts'] ) ) { $statuses[] = 'draft'; } $ids = empty( $spec['ids'] ) ? array() : array_values( array_filter( array_map( 'intval', (array) $spec['ids'] ) ) ); $id_list = implode( ',', $ids ); // Source posts only: no group row, or the row is the group's source. $sources = $wpdb->get_col( // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->prepare( "SELECT p.ID FROM %i p LEFT JOIN %i g ON g.object_type = 'post' AND g.object_id = p.ID WHERE INSTR( CONCAT( ',', %s, ',' ), CONCAT( ',', p.post_type, ',' ) ) > 0 AND INSTR( CONCAT( ',', %s, ',' ), CONCAT( ',', p.post_status, ',' ) ) > 0 AND ( g.id IS NULL OR g.group_id = g.object_id ) AND ( %s = '' OR INSTR( CONCAT( ',', %s, ',' ), CONCAT( ',', p.ID, ',' ) ) > 0 ) ORDER BY p.post_type = 'page' DESC, p.menu_order ASC, p.ID ASC", $wpdb->posts, $wpdb->tp_translation_groups, implode( ',', $types ), implode( ',', $statuses ), $id_list, $id_list ) ); $tasks = array(); foreach ( $sources as $id ) { $members = Groups::members( 'post', (int) $id ); foreach ( $langs as $lang ) { $row = $members[ $lang ] ?? null; if ( $row && ! get_post_status( (int) $row['object_id'] ) ) { $row = null; // Translation was deleted. } $need = 'all' === $mode || ! $row || ( 'update' === $mode && Groups::STATUS_OUTDATED === $row['status'] ); if ( $need ) { $tasks[] = array( (int) $id, $lang ); } } } return $tasks; } /** * Estimate characters for a job spec (samples large sites). * * @return array{tasks:int, chars:int, sampled:bool} */ public function estimate( array $spec ): array { $tasks = self::tasks( $spec ); $total = count( $tasks ); $sample = $total > 300 ? array_slice( $tasks, 0, 300 ) : $tasks; $chars = 0; foreach ( $sample as list( $id, $lang ) ) { $post = get_post( $id ); if ( $post ) { $chars += $this->posts->estimate( $post, $lang ); } } if ( $total > count( $sample ) && $sample ) { $chars = (int) round( $chars / count( $sample ) * $total ); } return array( 'tasks' => $total, 'chars' => $chars, 'sampled' => $total > count( $sample ), ); } /** * Create and enqueue a job. */ public function create( array $spec, int $estimate = 0 ): int { global $wpdb; $tasks = self::tasks( $spec ); $now = current_time( 'mysql', true ); $wpdb->insert( // phpcs:ignore WordPress.DB self::table(), array( 'type' => 'bulk', 'status' => $tasks ? self::STATUS_QUEUED : self::STATUS_DONE, 'payload' => wp_json_encode( $spec ), 'total' => count( $tasks ), 'credits_estimated' => $estimate, 'created_by' => get_current_user_id(), 'created_at' => $now, 'updated_at' => $now, ) ); $job_id = (int) $wpdb->insert_id; $this->enqueue( $job_id, $tasks ); Logger::info( sprintf( 'Bulk job #%d created with %d tasks.', $job_id, count( $tasks ) ) ); return $job_id; } private function enqueue( int $job_id, array $tasks ): void { foreach ( $tasks as $i => list( $post_id, $lang ) ) { as_schedule_single_action( time() + (int) floor( $i / 20 ), self::ACTION, array( $job_id, $post_id, $lang ), self::group( $job_id ) ); } } public static function get( int $job_id ): ?array { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE id = %d", $wpdb->tp_jobs, $job_id ), ARRAY_A ); // phpcs:ignore WordPress.DB return $row ? self::shape( $row ) : null; } public static function recent( int $limit = 20 ): array { global $wpdb; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i ORDER BY id DESC LIMIT %d", $wpdb->tp_jobs, $limit ), ARRAY_A ); // phpcs:ignore WordPress.DB return array_map( array( __CLASS__, 'shape' ), $rows ); } public static function active(): ?array { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE status IN (%s, %s, %s) ORDER BY id DESC LIMIT 1', $wpdb->tp_jobs, self::STATUS_QUEUED, self::STATUS_RUNNING, self::STATUS_PAUSED ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery return $row ? self::shape( $row ) : null; } private static function shape( array $row ): array { $spec = json_decode( (string) $row['payload'], true ) ?: array(); return array( 'id' => (int) $row['id'], 'status' => $row['status'], 'total' => (int) $row['total'], 'done' => (int) $row['done'], 'failed' => (int) $row['failed'], 'estimate' => (int) $row['credits_estimated'], 'error' => (string) $row['error'], 'spec' => $spec, 'created_at' => mysql_to_rfc3339( $row['created_at'] ), 'updated_at' => mysql_to_rfc3339( $row['updated_at'] ), ); } private static function update( int $job_id, array $data ): void { global $wpdb; $data['updated_at'] = current_time( 'mysql', true ); $wpdb->update( self::table(), $data, array( 'id' => $job_id ) ); // phpcs:ignore WordPress.DB } private static function increment( int $job_id, string $column ): void { global $wpdb; $now = current_time( 'mysql', true ); if ( 'failed' === $column ) { $wpdb->query( $wpdb->prepare( "UPDATE %i SET failed = failed + 1, updated_at = %s WHERE id = %d", $wpdb->tp_jobs, $now, $job_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } else { $wpdb->query( $wpdb->prepare( "UPDATE %i SET done = done + 1, updated_at = %s WHERE id = %d", $wpdb->tp_jobs, $now, $job_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } } public function pause( int $job_id, string $error = '' ): void { as_unschedule_all_actions( self::ACTION, null, self::group( $job_id ) ); self::update( $job_id, array( 'status' => self::STATUS_PAUSED, 'error' => $error ) ); } public function resume( int $job_id ): void { $job = self::get( $job_id ); if ( ! $job ) { return; } $spec = $job['spec']; $spec['mode'] = 'all' === ( $spec['mode'] ?? '' ) ? 'update' : ( $spec['mode'] ?? 'missing' ); $tasks = self::tasks( $spec ); self::update( $job_id, array( 'status' => $tasks ? self::STATUS_QUEUED : self::STATUS_DONE, 'error' => '', 'total' => $job['done'] + $job['failed'] + count( $tasks ), ) ); $this->enqueue( $job_id, $tasks ); } public function cancel( int $job_id ): void { as_unschedule_all_actions( self::ACTION, null, self::group( $job_id ) ); self::update( $job_id, array( 'status' => self::STATUS_CANCELLED ) ); } /** * Action Scheduler callback for one task. */ public function run_task( $job_id, $post_id, $lang ): void { $job_id = (int) $job_id; $job = self::get( $job_id ); if ( ! $job || in_array( $job['status'], array( self::STATUS_PAUSED, self::STATUS_CANCELLED ), true ) ) { return; } if ( self::STATUS_QUEUED === $job['status'] ) { self::update( $job_id, array( 'status' => self::STATUS_RUNNING ) ); } $force = 'all' === ( $job['spec']['mode'] ?? '' ); try { $this->posts->translate( (int) $post_id, (string) $lang, array( 'force' => $force ) ); self::increment( $job_id, 'done' ); } catch ( ApiException $e ) { if ( in_array( $e->reason(), array( ApiException::NO_CREDITS, ApiException::INVALID_KEY, ApiException::NO_KEY ), true ) ) { $this->pause( $job_id, $e->getMessage() ); Logger::error( sprintf( 'Job #%d paused: %s', $job_id, $e->getMessage() ) ); return; } if ( $e->is_retryable() ) { as_schedule_single_action( time() + 60, self::ACTION, array( $job_id, $post_id, $lang ), self::group( $job_id ) ); return; } self::increment( $job_id, 'failed' ); Logger::error( sprintf( 'Post %d → %s failed: %s', $post_id, $lang, $e->getMessage() ), array( 'job' => $job_id ) ); } catch ( \Throwable $e ) { self::increment( $job_id, 'failed' ); Logger::error( sprintf( 'Post %d → %s failed: %s', $post_id, $lang, $e->getMessage() ), array( 'job' => $job_id ) ); } $this->maybe_finish( $job_id ); } private function maybe_finish( int $job_id ): void { $job = self::get( $job_id ); if ( $job && $job['done'] + $job['failed'] >= $job['total'] && self::STATUS_RUNNING === $job['status'] ) { self::update( $job_id, array( 'status' => $job['failed'] && ! $job['done'] ? self::STATUS_FAILED : self::STATUS_DONE ) ); Logger::info( sprintf( 'Bulk job #%d finished: %d translated, %d failed.', $job_id, $job['done'], $job['failed'] ) ); } } /** * Queue automatic translation of one post into all targets. */ public static function queue_auto( int $post_id ): void { foreach ( Languages::targets() as $lang ) { $args = array( $post_id, $lang ); if ( ! as_has_scheduled_action( self::AUTO_ACTION, $args, self::GROUP ) ) { as_enqueue_async_action( self::AUTO_ACTION, $args, self::GROUP ); } } } public function run_auto( $post_id, $lang ): void { try { $this->posts->translate( (int) $post_id, (string) $lang ); } catch ( ApiException $e ) { if ( $e->is_retryable() ) { as_schedule_single_action( time() + 120, self::AUTO_ACTION, array( (int) $post_id, (string) $lang ), self::GROUP ); return; } Logger::error( sprintf( 'Auto-translation of post %d → %s failed: %s', $post_id, $lang, $e->getMessage() ) ); } catch ( \Throwable $e ) { Logger::error( sprintf( 'Auto-translation of post %d → %s failed: %s', $post_id, $lang, $e->getMessage() ) ); } } }