settings = $settings; } /** * Hooks for the public player. Kept out of the constructor so REST handlers and * assistant tools can build an instance without registering anything twice. */ public function register_hooks() { add_filter( 'the_content', array($this, 'render_player'), 20 ); add_action( 'wp_enqueue_scripts', array($this, 'enqueue_front') ); add_action( 'before_delete_post', array($this, 'delete_for_post') ); add_action( self::CLEANUP_HOOK, array(__CLASS__, 'cleanup_stale') ); // Sites that updated without reactivating get the daily cleanup here. add_action( 'init', array(__CLASS__, 'schedule_cleanup') ); } // ------------------------------------------------------------------ // Options // ------------------------------------------------------------------ /** * Display name of an audio provider. * * @param string $provider Provider slug. * @return string */ public static function provider_label( $provider ) { switch ( $provider ) { case 'elevenlabs': return 'ElevenLabs'; case 'grok': return Providers::label( 'grok' ); case 'gemini': return Providers::label( 'gemini' ); } return ''; } /** * ElevenLabs models offered, best first. * * @return array */ public static function elevenlabs_models() { return array( 'eleven_v4' => __( 'Eleven v4 (most natural, recommended)', 'ai-featured-image-generator' ), 'eleven_v4_turbo' => __( 'Eleven v4 Turbo (half the price, faster)', 'ai-featured-image-generator' ), 'eleven_multilingual_v2' => __( 'Multilingual v2 (steady on long posts)', 'ai-featured-image-generator' ), ); } /** * Gemini text-to-speech models offered. * * @return array */ public static function gemini_models() { return array( 'gemini-3.8-flash-tts' => __( 'Gemini 3.8 Flash TTS (recommended)', 'ai-featured-image-generator' ), 'gemini-3.8-flash-lite-tts' => __( 'Gemini 3.8 Flash-Lite TTS (cheaper)', 'ai-featured-image-generator' ), ); } /** * Gemini's prebuilt voices with Google's one-word description of each. * * @return array */ public static function gemini_voices() { return array( 'Charon' => __( 'Informative', 'ai-featured-image-generator' ), 'Kore' => __( 'Firm', 'ai-featured-image-generator' ), 'Puck' => __( 'Upbeat', 'ai-featured-image-generator' ), 'Zephyr' => __( 'Bright', 'ai-featured-image-generator' ), 'Fenrir' => __( 'Excitable', 'ai-featured-image-generator' ), 'Leda' => __( 'Youthful', 'ai-featured-image-generator' ), 'Orus' => __( 'Firm', 'ai-featured-image-generator' ), 'Aoede' => __( 'Breezy', 'ai-featured-image-generator' ), 'Callirrhoe' => __( 'Easy-going', 'ai-featured-image-generator' ), 'Autonoe' => __( 'Bright', 'ai-featured-image-generator' ), 'Enceladus' => __( 'Breathy', 'ai-featured-image-generator' ), 'Iapetus' => __( 'Clear', 'ai-featured-image-generator' ), 'Umbriel' => __( 'Easy-going', 'ai-featured-image-generator' ), 'Algieba' => __( 'Smooth', 'ai-featured-image-generator' ), 'Despina' => __( 'Smooth', 'ai-featured-image-generator' ), 'Erinome' => __( 'Clear', 'ai-featured-image-generator' ), 'Algenib' => __( 'Gravelly', 'ai-featured-image-generator' ), 'Rasalgethi' => __( 'Informative', 'ai-featured-image-generator' ), 'Laomedeia' => __( 'Upbeat', 'ai-featured-image-generator' ), 'Achernar' => __( 'Soft', 'ai-featured-image-generator' ), 'Alnilam' => __( 'Firm', 'ai-featured-image-generator' ), 'Schedar' => __( 'Even', 'ai-featured-image-generator' ), 'Gacrux' => __( 'Mature', 'ai-featured-image-generator' ), 'Pulcherrima' => __( 'Forward', 'ai-featured-image-generator' ), 'Achird' => __( 'Friendly', 'ai-featured-image-generator' ), 'Zubenelgenubi' => __( 'Casual', 'ai-featured-image-generator' ), 'Vindemiatrix' => __( 'Gentle', 'ai-featured-image-generator' ), 'Sadachbia' => __( 'Lively', 'ai-featured-image-generator' ), 'Sadaltager' => __( 'Knowledgeable', 'ai-featured-image-generator' ), 'Sulafat' => __( 'Warm', 'ai-featured-image-generator' ), ); } /** * Default text above the player. * * @return string */ public static function default_label() { return __( 'Listen to this post', 'ai-featured-image-generator' ); } /** * Audio settings with defaults applied. Never includes an API key. * * @param array $overrides Optional provider, model and voice for this call only. * @return array */ public function config( $overrides = array() ) { $s = $this->settings->get_settings(); $s = ( is_array( $s ) ? $s : array() ); $provider = ( isset( $overrides['provider'] ) ? (string) $overrides['provider'] : (( isset( $s['audio_provider'] ) ? (string) $s['audio_provider'] : self::DEFAULT_PROVIDER )) ); if ( !in_array( $provider, self::PROVIDERS, true ) ) { $provider = self::DEFAULT_PROVIDER; } $model = ''; $voice = ''; $voice_name = ''; if ( 'elevenlabs' === $provider ) { $model = ( isset( $s['elevenlabs_model'] ) ? (string) $s['elevenlabs_model'] : self::DEFAULT_ELEVENLABS_MODEL ); if ( !isset( self::elevenlabs_models()[$model] ) ) { $model = self::DEFAULT_ELEVENLABS_MODEL; } $voice = ( isset( $s['elevenlabs_voice'] ) ? (string) $s['elevenlabs_voice'] : '' ); $voice_name = ( isset( $s['elevenlabs_voice_name'] ) ? (string) $s['elevenlabs_voice_name'] : '' ); } elseif ( 'grok' === $provider ) { $voice = ( !empty( $s['grok_voice'] ) ? (string) $s['grok_voice'] : self::DEFAULT_GROK_VOICE ); $voice_name = ( !empty( $s['grok_voice_name'] ) ? (string) $s['grok_voice_name'] : ucfirst( $voice ) ); } else { $model = ( isset( $s['gemini_tts_model'] ) ? (string) $s['gemini_tts_model'] : self::DEFAULT_GEMINI_MODEL ); if ( !isset( self::gemini_models()[$model] ) ) { $model = self::DEFAULT_GEMINI_MODEL; } $voice = ( isset( $s['gemini_voice'] ) ? (string) $s['gemini_voice'] : self::DEFAULT_GEMINI_VOICE ); if ( !isset( self::gemini_voices()[$voice] ) ) { $voice = self::DEFAULT_GEMINI_VOICE; } $voice_name = $voice; } if ( isset( $overrides['model'] ) && '' !== (string) $overrides['model'] ) { $wanted = (string) $overrides['model']; if ( 'elevenlabs' === $provider && isset( self::elevenlabs_models()[$wanted] ) || 'gemini' === $provider && isset( self::gemini_models()[$wanted] ) ) { $model = $wanted; } } if ( isset( $overrides['voice'] ) && '' !== (string) $overrides['voice'] ) { $voice = (string) $overrides['voice']; $voice_name = ( isset( $overrides['voice_name'] ) && '' !== (string) $overrides['voice_name'] ? (string) $overrides['voice_name'] : $voice ); if ( 'gemini' === $provider && !isset( self::gemini_voices()[$voice] ) ) { $voice = self::DEFAULT_GEMINI_VOICE; $voice_name = $voice; } } $label = ( isset( $s['audio_label'] ) && '' !== trim( (string) $s['audio_label'] ) ? (string) $s['audio_label'] : self::default_label() ); return array( 'enabled' => ( isset( $s['audio_enabled'] ) ? (bool) $s['audio_enabled'] : true ), 'provider' => $provider, 'model' => $model, 'voice' => $voice, 'voice_name' => $voice_name, 'label' => $label, 'post_types' => $this->post_types( $s ), ); } /** * Post types that can have a recording: the chosen ones that still have the plugin enabled. * * @param array|null $s Settings, read when null. * @return string[] */ public function post_types( $s = null ) { if ( null === $s ) { $s = $this->settings->get_settings(); } // A saved choice may include WooCommerce products; with nothing saved, only the // enabled types get a player, so products never get one by default. if ( isset( $s['audio_post_types'] ) && is_array( $s['audio_post_types'] ) ) { return array_values( array_intersect( $this->settings->get_content_post_types(), $s['audio_post_types'] ) ); } return array_values( $this->settings->get_enabled_post_types() ); } /** * API key for an audio provider. Grok and Gemini reuse the keys from the General tab. * * @param string $provider Provider slug. * @return string */ private function api_key( $provider ) { $s = $this->settings->get_settings(); if ( 'elevenlabs' === $provider ) { return ( isset( $s['elevenlabs_api_key'] ) ? trim( (string) $s['elevenlabs_api_key'] ) : '' ); } if ( 'grok' === $provider || 'gemini' === $provider ) { return trim( (string) Providers::get_api_key( ( is_array( $s ) ? $s : array() ), $provider ) ); } return ''; } /** * Whether the provider has a key saved. * * @param string $provider Provider slug. * @return bool */ public function has_key( $provider ) { return '' !== $this->api_key( $provider ); } /** * Upgrade error shared by every Pro entry point. * * @return \WP_Error */ private function premium_error() { return new \WP_Error('premium_required', __( 'Listen to this post is a Pro feature. Please upgrade to turn posts into audio.', 'ai-featured-image-generator' ), array( 'status' => 403, )); } /** * Error for a missing key, pointing at the tab that holds it. * * @param string $provider Provider slug. * @return \WP_Error */ private function no_key_error( $provider ) { $tab = ( 'elevenlabs' === $provider ? __( 'the Audio tab', 'ai-featured-image-generator' ) : __( 'the General tab', 'ai-featured-image-generator' ) ); return new \WP_Error('audio_no_key', sprintf( /* translators: 1: provider name, 2: settings tab name */ __( 'Add your %1$s API key on %2$s in AI Images settings first.', 'ai-featured-image-generator' ), self::provider_label( $provider ), $tab ), array( 'status' => 400, )); } // ------------------------------------------------------------------ // Text // ------------------------------------------------------------------ /** * The words that are read aloud: the title, then the body as plain paragraphs. * * @param \WP_Post|int $post Post. * @return string Paragraphs separated by a blank line. */ public function extract_text( $post ) { $post = get_post( $post ); if ( !$post ) { return ''; } $content = strip_shortcodes( (string) $post->post_content ); // Block comments, code and embedded scripts are never read aloud. $content = preg_replace( '//s', '', $content ); $content = preg_replace( '#<(script|style|pre|svg|noscript|figcaption)\\b[^>]*>.*?#is', ' ', $content ); // Block-level ends become paragraph breaks so headings and list items get a pause. $content = preg_replace( '#|#i', "\$0\n\n", $content ); $content = wp_strip_all_tags( $content, false ); $paragraphs = array(); $title = trim( wp_strip_all_tags( (string) $post->post_title ) ); if ( '' !== $title ) { $paragraphs[] = $title; } $content = str_replace( array("\r\n", "\r"), "\n", (string) $content ); foreach ( preg_split( '/\\n\\s*\\n/', $content ) as $para ) { $paragraphs[] = $para; } $out = array(); foreach ( $paragraphs as $para ) { $para = html_entity_decode( $para, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); $para = preg_replace( '/[\\s\\x{00A0}]+/u', ' ', $para ); $para = trim( (string) $para ); if ( '' === $para ) { continue; } // A heading or list item without an end mark would run into the next line. if ( !preg_match( '/[.!?:;\\x{2026}"\'\\x{201D}\\x{2019})\\]]$/u', $para ) ) { $para .= '.'; } $out[] = $para; } return implode( "\n\n", $out ); } /** * Hash of the text that would be read now. * * @param \WP_Post|int $post Post. * @return string */ public function text_hash( $post ) { return md5( $this->extract_text( $post ) ); } /** * Split text into pieces of at most $limit characters, on paragraph, then sentence, * then word boundaries. * * @param string $text Paragraphs separated by a blank line. * @param int $limit Characters per piece. * @return string[] */ public static function chunk_text( $text, $limit = self::CHUNK_CHARS ) { $chunks = array(); $current = ''; foreach ( explode( "\n\n", (string) $text ) as $para ) { $para = trim( $para ); if ( '' === $para ) { continue; } foreach ( self::split_long( $para, $limit ) as $piece ) { if ( '' === $current ) { $current = $piece; } elseif ( mb_strlen( $current ) + 2 + mb_strlen( $piece ) <= $limit ) { $current .= "\n\n" . $piece; } else { $chunks[] = $current; $current = $piece; } } } if ( '' !== $current ) { $chunks[] = $current; } return $chunks; } /** * Break one paragraph that is longer than the limit. * * @param string $para Paragraph. * @param int $limit Characters per piece. * @return string[] */ private static function split_long( $para, $limit ) { if ( mb_strlen( $para ) <= $limit ) { return array($para); } $out = array(); $cur = ''; foreach ( preg_split( '/(?<=[.!?])\\s+/u', $para ) as $sentence ) { while ( mb_strlen( $sentence ) > $limit ) { $cut = mb_strrpos( mb_substr( $sentence, 0, $limit ), ' ' ); if ( !$cut ) { $cut = $limit; } if ( '' !== $cur ) { $out[] = $cur; $cur = ''; } $out[] = trim( mb_substr( $sentence, 0, $cut ) ); $sentence = trim( mb_substr( $sentence, $cut ) ); } if ( '' === $sentence ) { continue; } if ( '' === $cur ) { $cur = $sentence; } elseif ( mb_strlen( $cur ) + 1 + mb_strlen( $sentence ) <= $limit ) { $cur .= ' ' . $sentence; } else { $out[] = $cur; $cur = $sentence; } } if ( '' !== $cur ) { $out[] = $cur; } return $out; } // ------------------------------------------------------------------ // Status and estimate // ------------------------------------------------------------------ /** * "4 min 12 s" style length. * * @param int $seconds Seconds. * @return string */ public static function format_duration( $seconds ) { $seconds = max( 0, (int) round( $seconds ) ); if ( $seconds < 60 ) { /* translators: %d: seconds */ return sprintf( __( '%d s', 'ai-featured-image-generator' ), $seconds ); } $minutes = (int) floor( $seconds / 60 ); $rest = $seconds % 60; if ( 0 === $rest ) { /* translators: %d: minutes */ return sprintf( __( '%d min', 'ai-featured-image-generator' ), $minutes ); } /* translators: 1: minutes, 2: seconds */ return sprintf( __( '%1$d min %2$d s', 'ai-featured-image-generator' ), $minutes, $rest ); } /** * Attachment id of the post's recording, or 0 when there is none (or it was deleted). * * @param int $post_id Post ID. * @return int */ public function attachment_id( $post_id ) { $id = (int) get_post_meta( $post_id, self::META_ID, true ); if ( $id && 'attachment' === get_post_type( $id ) ) { return $id; } return 0; } /** * Everything the post editor shows about the post's recording. * * @param \WP_Post|int $post Post. * @return array */ public function status( $post ) { $post = get_post( $post ); if ( !$post ) { return array( 'has_audio' => false, ); } $att = $this->attachment_id( $post->ID ); $provider = (string) get_post_meta( $post->ID, self::META_PROVIDER, true ); $seconds = (int) get_post_meta( $post->ID, self::META_SECONDS, true ); return array( 'has_audio' => $att > 0, 'attachment_id' => $att, 'url' => ( $att ? (string) wp_get_attachment_url( $att ) : '' ), 'stale' => $att > 0 && get_post_meta( $post->ID, self::META_HASH, true ) !== $this->text_hash( $post ), 'hidden' => '1' === (string) get_post_meta( $post->ID, self::META_HIDDEN, true ), 'seconds' => $seconds, 'duration' => ( $att ? self::format_duration( $seconds ) : '' ), 'chars' => (int) get_post_meta( $post->ID, self::META_CHARS, true ), 'provider' => $provider, 'provider_label' => self::provider_label( $provider ), 'voice_name' => (string) get_post_meta( $post->ID, self::META_VOICE_NAME, true ), ); } /** * Rough length and price of reading the post with the current settings. * * @param \WP_Post|int $post Post. * @return array chars, chunks, seconds, cost (float), line (sentence for the editor). */ public function estimate( $post ) { $cfg = $this->config(); $text = $this->extract_text( $post ); $chars = mb_strlen( $text ); $seconds = (int) ceil( $chars / self::CHARS_PER_SECOND ); $cost = self::estimate_cost( $cfg['provider'], $cfg['model'], $chars ); $label = self::provider_label( $cfg['provider'] ); if ( 0 === $chars ) { $line = __( 'This post has no text to read yet.', 'ai-featured-image-generator' ); } else { $price = ( $cost < 0.01 ? __( 'Under $0.01', 'ai-featured-image-generator' ) : sprintf( __( 'About %s', 'ai-featured-image-generator' ), '$' . number_format_i18n( $cost, 2 ) ) ); $line = sprintf( /* translators: 1: number of characters, 2: length such as "4 min" */ __( 'About %1$s characters, roughly %2$s of audio.', 'ai-featured-image-generator' ), number_format_i18n( $chars ), self::format_duration( $seconds ) ) . ' '; if ( 'gemini' === $cfg['provider'] ) { $line .= sprintf( /* translators: 1: price such as "About $0.02" or "Under $0.01", 2: provider name */ __( '%1$s with %2$s, or free within Google\'s free tier.', 'ai-featured-image-generator' ), $price, $label ); } else { $line .= sprintf( /* translators: 1: price such as "About $0.50" or "Under $0.01", 2: provider name */ __( '%1$s with %2$s, billed to your %2$s account.', 'ai-featured-image-generator' ), $price, $label ); } if ( $chars > self::MAX_CHARS ) { $line = self::too_long_message(); } } return array( 'chars' => $chars, 'chunks' => ( $chars ? count( self::chunk_text( $text ) ) : 0 ), 'seconds' => $seconds, 'cost' => $cost, 'line' => $line, ); } /** * Estimated price in US dollars. * * @param string $provider Provider slug. * @param string $model Model id. * @param int $chars Characters. * @return float */ public static function estimate_cost( $provider, $model, $chars ) { if ( 'elevenlabs' === $provider ) { $per_1k = ( 'eleven_v4_turbo' === $model ? 0.04 : 0.08 ); return $chars / 1000 * $per_1k; } if ( 'grok' === $provider ) { return $chars / 1000 * 0.015; } if ( 'gemini' === $provider ) { // Billed per audio token, 25 tokens per second of speech. $per_million = ( 'gemini-3.8-flash-lite-tts' === $model ? 12.0 : 18.0 ); return $chars / self::CHARS_PER_SECOND * 25 / 1000000 * $per_million; } return 0.0; } /** * @return string */ private static function too_long_message() { return sprintf( /* translators: %s: maximum number of characters */ __( 'This post is too long for one recording (more than %s characters).', 'ai-featured-image-generator' ), number_format_i18n( self::MAX_CHARS ) ); } // ------------------------------------------------------------------ // Generation // ------------------------------------------------------------------ /** * Whether recordings are allowed for this post's type. * * @param \WP_Post $post Post. * @return bool */ public function post_type_allowed( $post ) { return in_array( $post->post_type, $this->post_types(), true ); } /** * Make the next part of the post's recording. The first call (no job) starts a new * recording; each later call passes the job id it was given, until done is true. * * @param int $post_id Post ID. * @param string $job_id Job id from the previous call, or '' to start. * @return array|\WP_Error */ public function step( $post_id, $job_id = '' ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * Make every part in one go (assistants and other callers that can wait). * * @param int $post_id Post ID. * @return array|\WP_Error Same as the last step(). */ public function generate_all( $post_id ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * The id of the post's unfinished recording when it can carry on: the text, provider, * model and voice are the same as now, and every part made so far is still on disk. * * @param int $post_id Post ID. * @return string Job id, or '' to start a new recording. */ private function resumable_job( $post_id ) { $job = get_transient( self::JOB_TRANSIENT . (int) $post_id ); if ( !is_array( $job ) || empty( $job['job'] ) || !isset( $job['done'], $job['total'], $job['hash'], $job['provider'], $job['model'], $job['voice'] ) ) { return ''; } $post = get_post( $post_id ); if ( !$post || $this->text_hash( $post ) !== $job['hash'] ) { return ''; } $cfg = $this->config(); if ( $cfg['provider'] !== $job['provider'] || $cfg['model'] !== $job['model'] || '' !== $cfg['voice'] && $cfg['voice'] !== $job['voice'] ) { return ''; } $parts = glob( $this->job_dir( $post_id, $job['job'] ) . '/part-*.bin' ); // One part more than recorded is fine: the request that made it died before it could // note it, and the next part simply writes over it. if ( !is_array( $parts ) || count( $parts ) < (int) $job['done'] ) { return ''; } return (string) $job['job']; } /** * Gives the next part a full time budget when PHP has a time limit. A limit of 0 * (no limit, as on the command line) is left alone, and a limit is never lowered. */ private static function extend_time_limit() { if ( !function_exists( 'set_time_limit' ) ) { return; } $limit = (int) ini_get( 'max_execution_time' ); if ( $limit > 0 ) { @set_time_limit( max( $limit, self::LOCK_TTL ) ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, Squiz.PHP.DiscouragedFunctions.Discouraged } } /** * Takes the post's recording lock. Of two requests at the same moment only one gets it: * the row is added with INSERT IGNORE (or wp_cache_add() with a shared object cache), * not read first and written after. It lasts LOCK_TTL seconds at most, so a request * that died holding it never blocks the post for long. * * @param int $post_id Post ID. * @return bool True when this request holds the lock. */ private static function acquire_lock( $post_id ) { $name = self::LOCK_PREFIX . (int) $post_id; if ( wp_using_ext_object_cache() ) { return (bool) wp_cache_add( $name, time() + self::LOCK_TTL, 'aifi_locks', self::LOCK_TTL ); } global $wpdb; $now = time(); // A lock left behind by a request that died. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND CAST( option_value AS UNSIGNED ) < %d", $name, $now ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $added = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} ( option_name, option_value, autoload ) VALUES ( %s, %s, 'no' )", $name, (string) ($now + self::LOCK_TTL) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return 1 === (int) $added; } /** * Releases the post's recording lock. * * @param int $post_id Post ID. */ private static function release_lock( $post_id ) { $name = self::LOCK_PREFIX . (int) $post_id; if ( wp_using_ext_object_cache() ) { wp_cache_delete( $name, 'aifi_locks' ); return; } delete_option( $name ); } /** * @param \WP_Post $post Post. * @param string $job_id Job id or ''. * @return array|\WP_Error */ private function run_step( $post, $job_id ) { $job = false; if ( '' !== $job_id ) { $job = get_transient( self::JOB_TRANSIENT . $post->ID ); if ( !is_array( $job ) || !isset( $job['job'] ) || $job['job'] !== $job_id ) { return new \WP_Error('audio_job_expired', __( 'This recording was interrupted. Click Generate audio to start again.', 'ai-featured-image-generator' ), array( 'status' => 410, )); } } else { $job = $this->start_job( $post ); if ( is_wp_error( $job ) ) { return $job; } } if ( (int) $job['done'] >= (int) $job['total'] ) { // Every part was made, but the file could not be saved last time: only save it. return $this->finish_job( $post, $job ); } $index = (int) $job['done']; // Check the folder before paying for the part, so a full or locked disk costs nothing. $dir = $this->job_dir( $post->ID, $job['job'] ); if ( !is_dir( $dir ) || !wp_is_writable( $dir ) ) { return new \WP_Error('audio_write_failed', __( 'Could not write the audio file. Check that the uploads folder is writable.', 'ai-featured-image-generator' )); } $part = $this->synthesize( $job['chunks'][$index], $job ); if ( is_wp_error( $part ) ) { // The job stays, so trying again carries on from this part. return $part; } if ( '' === $job['format'] ) { $job['format'] = $part['format']; $job['rate'] = ( isset( $part['rate'] ) ? (int) $part['rate'] : 0 ); $job['channels'] = ( isset( $part['channels'] ) ? (int) $part['channels'] : 1 ); $job['bits'] = ( isset( $part['bits'] ) ? (int) $part['bits'] : 16 ); } elseif ( $job['format'] !== $part['format'] ) { // This recording cannot carry on, so the next click starts a new one. $this->clear_jobs( $post->ID ); return new \WP_Error('audio_failed', __( 'The provider changed the audio format halfway. Click Generate audio to start again.', 'ai-featured-image-generator' )); } if ( !is_dir( $dir ) || false === file_put_contents( $dir . '/' . sprintf( 'part-%04d.bin', $index ), $part['bytes'] ) ) { return new \WP_Error('audio_write_failed', __( 'Could not write the audio file. Check that the uploads folder is writable.', 'ai-featured-image-generator' )); } $job['seconds'] += $part['seconds']; $job['done'] = $index + 1; // Kept until the file is saved, so a failed save is tried again without new parts. set_transient( self::JOB_TRANSIENT . $post->ID, $job, self::JOB_TTL ); if ( $job['done'] < $job['total'] ) { return array( 'done' => false, 'job' => $job['job'], 'next' => $job['done'], 'total' => $job['total'], ); } return $this->finish_job( $post, $job ); } /** * Read the post and set up a new recording, replacing any unfinished one. * * @param \WP_Post $post Post. * @return array|\WP_Error Job state. */ private function start_job( $post ) { // The recording is a plain file in the uploads folder that anyone with its address can // play, so a password-protected post is never read aloud. if ( post_password_required( $post ) || '' !== (string) $post->post_password ) { return new \WP_Error('audio_protected', __( 'This post is password protected, so it is not read aloud: the recording could be played without the password.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } $cfg = $this->config(); if ( !$this->has_key( $cfg['provider'] ) ) { return $this->no_key_error( $cfg['provider'] ); } $text = $this->extract_text( $post ); if ( '' === $text ) { return new \WP_Error('audio_empty', __( 'This post has no text to read yet.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } $chars = mb_strlen( $text ); if ( $chars > self::MAX_CHARS ) { return new \WP_Error('audio_too_long', self::too_long_message(), array( 'status' => 400, )); } if ( '' === $cfg['voice'] ) { // No voice picked yet: take the first one the account offers. $voices = $this->voices( $cfg['provider'] ); if ( is_wp_error( $voices ) ) { return $voices; } if ( empty( $voices ) ) { return new \WP_Error('audio_no_voice', __( 'Choose a voice on the Audio tab first.', 'ai-featured-image-generator' ), array( 'status' => 400, )); } $cfg['voice'] = $voices[0]['id']; $cfg['voice_name'] = $voices[0]['name']; } $this->clear_jobs( $post->ID ); $job_id = strtolower( wp_generate_password( 12, false, false ) ); $dir = $this->job_dir( $post->ID, $job_id ); if ( !wp_mkdir_p( $dir ) ) { return new \WP_Error('audio_write_failed', __( 'Could not write the audio file. Check that the uploads folder is writable.', 'ai-featured-image-generator' )); } self::protect_dir( dirname( $dir ) ); $chunks = self::chunk_text( $text ); $job = array( 'job' => $job_id, 'post_id' => $post->ID, 'chunks' => $chunks, 'total' => count( $chunks ), 'done' => 0, 'hash' => md5( $text ), 'chars' => $chars, 'provider' => $cfg['provider'], 'model' => $cfg['model'], 'voice' => $cfg['voice'], 'voice_name' => $cfg['voice_name'], 'format' => '', 'rate' => 0, 'channels' => 1, 'bits' => 16, 'seconds' => 0.0, ); set_transient( self::JOB_TRANSIENT . $post->ID, $job, self::JOB_TTL ); return $job; } /** * Join the parts, save the file to the Media Library and point the post at it. * * @param \WP_Post $post Post. * @param array $job Finished job. * @return array|\WP_Error */ private function finish_job( $post, $job ) { $dir = $this->job_dir( $post->ID, $job['job'] ); $parts = glob( $dir . '/part-*.bin' ); $parts = ( is_array( $parts ) ? $parts : array() ); sort( $parts ); if ( count( $parts ) !== (int) $job['total'] ) { $this->clear_jobs( $post->ID ); return new \WP_Error('audio_failed', __( 'Some parts of the recording are missing. Click Generate audio to start again.', 'ai-featured-image-generator' )); } require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; // One part at a time, so a long recording never sits in memory whole. $tmp = wp_tempnam( 'aifi-audio-' ); $ext = 'mp3'; $header = ''; if ( 'pcm' === $job['format'] ) { $ext = 'wav'; $total = 0; foreach ( $parts as $part ) { $total += (int) filesize( $part ); } $header = self::wav_header( $total, ( $job['rate'] ? $job['rate'] : 24000 ), $job['channels'], $job['bits'] ); } $written = ( $tmp ? file_put_contents( $tmp, $header ) : false ); foreach ( $parts as $part ) { if ( false === $written ) { break; } $written = file_put_contents( $tmp, (string) file_get_contents( $part ), FILE_APPEND ); } // The parts stay until the file is in the Media Library, so a failure here can be // retried without asking the provider again. if ( false === $written ) { if ( $tmp && file_exists( $tmp ) ) { wp_delete_file( $tmp ); } return new \WP_Error('audio_write_failed', __( 'Could not write the audio file. Check that the uploads folder is writable.', 'ai-featured-image-generator' )); } $title = trim( wp_strip_all_tags( (string) $post->post_title ) ); $basename = sanitize_file_name( ( '' !== $title ? sanitize_title( $title ) : 'post-' . $post->ID ) ); $att = media_handle_sideload( array( 'name' => $basename . '-audio-' . strtolower( wp_generate_password( 8, false ) ) . '.' . $ext, 'tmp_name' => $tmp, ), $post->ID, null, array( 'post_title' => sprintf( /* translators: %s: post title */ __( '%s (audio)', 'ai-featured-image-generator' ), /* translators: %d: post ID */ ( '' !== $title ? $title : sprintf( __( 'Post %d', 'ai-featured-image-generator' ), $post->ID ) ) ), ) ); if ( file_exists( $tmp ) ) { wp_delete_file( $tmp ); } if ( is_wp_error( $att ) ) { return new \WP_Error('audio_save_failed', $att->get_error_message()); } $this->clear_jobs( $post->ID ); update_post_meta( $att, self::META_FOR, $post->ID ); Podcast::remember_guid( $post->ID ); // Replace the previous recording, but only a file this feature made for this post. $old = $this->attachment_id( $post->ID ); if ( $old && $old !== (int) $att && (int) get_post_meta( $old, self::META_FOR, true ) === (int) $post->ID ) { wp_delete_attachment( $old, true ); } $seconds = (int) round( $job['seconds'] ); update_post_meta( $post->ID, self::META_ID, (int) $att ); update_post_meta( $post->ID, self::META_HASH, $job['hash'] ); update_post_meta( $post->ID, self::META_PROVIDER, $job['provider'] ); update_post_meta( $post->ID, self::META_MODEL, $job['model'] ); update_post_meta( $post->ID, self::META_VOICE, $job['voice'] ); update_post_meta( $post->ID, self::META_VOICE_NAME, wp_slash( $job['voice_name'] ) ); update_post_meta( $post->ID, self::META_CHARS, (int) $job['chars'] ); update_post_meta( $post->ID, self::META_SECONDS, $seconds ); update_post_meta( $post->ID, self::META_TIME, time() ); /** * Fires after a post's recording is saved. * * @param int $attachment_id Audio attachment ID. * @param int $post_id Post ID. */ do_action( 'aifi_after_generate_audio', (int) $att, $post->ID ); return array( 'done' => true, 'attachment_id' => (int) $att, 'url' => (string) wp_get_attachment_url( $att ), 'seconds' => $seconds, 'chars' => (int) $job['chars'], 'provider' => $job['provider'], 'voice' => $job['voice_name'], 'status' => $this->status( $post ), ); } /** * Remove the post's recording and the file this feature made for it. * * @param int $post_id Post ID. * @return bool True when something was removed. */ public function delete_audio( $post_id ) { $att = $this->attachment_id( $post_id ); $removed = false; if ( $att && (int) get_post_meta( $att, self::META_FOR, true ) === (int) $post_id ) { $removed = (bool) wp_delete_attachment( $att, true ); } foreach ( array( self::META_ID, self::META_HASH, self::META_PROVIDER, self::META_MODEL, self::META_VOICE, self::META_VOICE_NAME, self::META_CHARS, self::META_SECONDS, self::META_TIME ) as $key ) { $removed = delete_post_meta( $post_id, $key ) || $removed; } $this->clear_jobs( $post_id ); return $removed; } /** * Deletes the recording of a post that is being deleted for good (before_delete_post). * Only a file this feature made for that post is removed; its post meta goes with it. * * @param int $post_id Post being deleted. */ public function delete_for_post( $post_id ) { $post_id = (int) $post_id; $att = (int) get_post_meta( $post_id, self::META_ID, true ); if ( $att && $att !== $post_id && (int) get_post_meta( $att, self::META_FOR, true ) === $post_id ) { wp_delete_attachment( $att, true ); } if ( false !== get_transient( self::JOB_TRANSIENT . $post_id ) ) { $this->clear_jobs( $post_id ); } } /** * Hide or show the player on one post. * * @param int $post_id Post ID. * @param bool $hidden True hides it. */ public function set_hidden( $post_id, $hidden ) { if ( $hidden ) { update_post_meta( $post_id, self::META_HIDDEN, '1' ); } else { delete_post_meta( $post_id, self::META_HIDDEN ); } } // ------------------------------------------------------------------ // Providers // ------------------------------------------------------------------ /** * A short sample in the chosen voice, never saved. * * @param string $provider Provider slug. * @param string $voice Voice id. * @param string $model Model id. * @param string $api_key Key typed on the Audio tab but not saved yet, or ''. * @return array|\WP_Error mime and base64 data. */ public function preview( $provider, $voice, $model = '', $api_key = '' ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * Voices a provider offers, cached for 12 hours. * * @param string $provider Provider slug. * @param string $api_key Key typed on the Audio tab but not saved yet, or ''. * @param bool $refresh Skip the cache. * @return array|\WP_Error List of id, name and label. */ public function voices( $provider, $api_key = '', $refresh = false ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * Turn one piece of text into audio. * * @param string $text Text, at most CHUNK_CHARS characters. * @param array $cfg provider, model, voice, and optionally api_key. * @return array|\WP_Error format (mp3 or pcm), bytes, seconds, and rate, channels, bits for pcm. */ private function synthesize( $text, $cfg ) { if ( !Providers::can_use_premium() ) { return $this->premium_error(); } return $this->premium_error(); } /** * Send a request and turn every failure into a readable error. * * @param string $method GET or POST. * @param string $url URL. * @param array $headers Headers. * @param array|null $body JSON body. * @param int $timeout Seconds. * @param string $label Provider name for messages. * @return array|\WP_Error Response. */ private function http( $method, $url, $headers, $body, $timeout, $label ) { $args = array( 'method' => $method, 'headers' => $headers, 'timeout' => $timeout, 'httpversion' => '1.1', 'sslverify' => true, ); if ( null !== $body ) { $args['headers']['Content-Type'] = 'application/json'; $args['body'] = wp_json_encode( $body ); } /** This filter is documented in inc/class-generator.php */ $args = apply_filters( 'aifi_api_request_args', $args ); $response = wp_remote_request( $url, $args ); if ( is_wp_error( $response ) ) { if ( false !== stripos( $response->get_error_message(), 'timed out' ) ) { return new \WP_Error( 'api_timeout', /* translators: %s: provider name */ sprintf( __( '%s took too long to answer. Please try again.', 'ai-featured-image-generator' ), $label ) ); } return new \WP_Error( 'api_connection_error', /* translators: %s: provider name */ sprintf( __( 'Could not reach %s. Please check the connection and try again.', 'ai-featured-image-generator' ), $label ) ); } $code = (int) wp_remote_retrieve_response_code( $response ); if ( 200 === $code ) { return $response; } $data = json_decode( wp_remote_retrieve_body( $response ), true ); $message = ''; if ( isset( $data['detail']['message'] ) && is_string( $data['detail']['message'] ) ) { $message = $data['detail']['message']; } elseif ( isset( $data['detail'] ) && is_string( $data['detail'] ) ) { $message = $data['detail']; } elseif ( isset( $data['error']['message'] ) && is_string( $data['error']['message'] ) ) { $message = $data['error']['message']; } elseif ( isset( $data['error'] ) && is_string( $data['error'] ) ) { $message = $data['error']; } elseif ( isset( $data['message'] ) && is_string( $data['message'] ) ) { $message = $data['message']; } $message = mb_substr( trim( wp_strip_all_tags( $message ) ), 0, 300 ); if ( 401 === $code || 403 === $code ) { return new \WP_Error( 'api_auth_error', /* translators: %s: provider name */ sprintf( __( '%s did not accept the API key. Check the key and that text to speech is enabled for it.', 'ai-featured-image-generator' ), $label ) . (( '' !== $message ? ' (' . $message . ')' : '' )), array( 'status' => $code, ) ); } if ( 429 === $code ) { return new \WP_Error( 'api_quota_error', /* translators: %s: provider name */ sprintf( __( '%s says the account is over its limit or busy. Wait a moment or check your plan.', 'ai-featured-image-generator' ), $label ) . (( '' !== $message ? ' (' . $message . ')' : '' )), array( 'status' => 429, ) ); } return new \WP_Error('api_error', sprintf( /* translators: 1: provider name, 2: HTTP status code */ __( '%1$s returned an error (%2$d).', 'ai-featured-image-generator' ), $label, $code ) . (( '' !== $message ? ' ' . $message : '' )), array( 'status' => ( $code >= 400 && $code < 600 ? $code : 502 ), )); } /** * MP3 bytes from ElevenLabs or Grok. * * @param array|\WP_Error $response Response. * @param string $label Provider name. * @return array|\WP_Error */ private function mp3_part( $response, $label ) { if ( is_wp_error( $response ) ) { return $response; } $bytes = self::clean_mp3( (string) wp_remote_retrieve_body( $response ) ); if ( strlen( $bytes ) < 32 || 0 === self::mp3_frame_length( $bytes, 0 ) ) { return new \WP_Error( 'audio_bad_response', /* translators: %s: provider name */ sprintf( __( '%s did not send back audio. Please try again.', 'ai-featured-image-generator' ), $label ) ); } return array( 'format' => 'mp3', 'bytes' => $bytes, 'seconds' => self::mp3_duration( $bytes ), ); } /** * PCM samples from a Gemini reply (WAV or raw 16-bit PCM in inlineData). * * @param array|\WP_Error $response Response. * @param string $label Provider name. * @return array|\WP_Error */ private function gemini_part( $response, $label ) { if ( is_wp_error( $response ) ) { return $response; } $data = json_decode( wp_remote_retrieve_body( $response ), true ); $mime = ''; $bytes = ''; if ( isset( $data['candidates'][0]['content']['parts'] ) && is_array( $data['candidates'][0]['content']['parts'] ) ) { foreach ( $data['candidates'][0]['content']['parts'] as $part ) { $inline = ( isset( $part['inlineData'] ) ? $part['inlineData'] : (( isset( $part['inline_data'] ) ? $part['inline_data'] : null )) ); if ( is_array( $inline ) && !empty( $inline['data'] ) ) { $mime = ( isset( $inline['mimeType'] ) ? (string) $inline['mimeType'] : (( isset( $inline['mime_type'] ) ? (string) $inline['mime_type'] : '' )) ); $bytes = (string) base64_decode( (string) $inline['data'], true ); break; } } } if ( '' === $bytes ) { return new \WP_Error( 'audio_bad_response', /* translators: %s: provider name */ sprintf( __( '%s did not send back audio. Please try again.', 'ai-featured-image-generator' ), $label ) ); } $wav = self::parse_wav( $bytes ); if ( $wav ) { $pcm = $wav['pcm']; $rate = $wav['rate']; $channels = $wav['channels']; $bits = $wav['bits']; } else { $pcm = $bytes; $rate = ( preg_match( '/rate=(\\d+)/i', $mime, $m ) ? (int) $m[1] : 24000 ); $channels = 1; $bits = 16; } $per_second = max( 1, $rate * $channels * (int) ($bits / 8) ); return array( 'format' => 'pcm', 'bytes' => $pcm, 'rate' => $rate, 'channels' => $channels, 'bits' => $bits, 'seconds' => strlen( $pcm ) / $per_second, ); } // ------------------------------------------------------------------ // Audio files // ------------------------------------------------------------------ /** * Strip ID3 tags and the Xing/Info/VBRI header frame, so parts join into one * stream whose length players read correctly. * * @param string $bytes MP3 file. * @return string Plain MPEG frames. */ public static function clean_mp3( $bytes ) { if ( strlen( $bytes ) > 10 && 'ID3' === substr( $bytes, 0, 3 ) ) { $size = (ord( $bytes[6] ) & 0x7f) << 21 | (ord( $bytes[7] ) & 0x7f) << 14 | (ord( $bytes[8] ) & 0x7f) << 7 | ord( $bytes[9] ) & 0x7f; $total = 10 + $size + (( ord( $bytes[5] ) & 0x10 ? 10 : 0 )); $bytes = (string) substr( $bytes, $total ); } if ( strlen( $bytes ) > 128 && 'TAG' === substr( $bytes, -128, 3 ) ) { $bytes = (string) substr( $bytes, 0, -128 ); } // Skip anything before the first frame. $len = strlen( $bytes ); $pos = 0; while ( $pos + 4 <= $len && 0 === self::mp3_frame_length( $bytes, $pos ) ) { $pos++; } if ( $pos + 4 > $len ) { return $bytes; } $bytes = (string) substr( $bytes, $pos ); $frame = self::mp3_frame_length( $bytes, 0 ); if ( $frame > 0 && $frame <= strlen( $bytes ) ) { $b1 = ord( $bytes[1] ); $mpeg1 = 3 === ($b1 >> 3 & 3); $mono = 3 === (ord( $bytes[3] ) >> 6 & 3); $side = ( $mpeg1 ? ( $mono ? 17 : 32 ) : (( $mono ? 9 : 17 )) ); $tag = substr( $bytes, 4 + $side, 4 ); $is_vbri = 'VBRI' === substr( $bytes, 36, 4 ); if ( 'Xing' === $tag || 'Info' === $tag || $is_vbri ) { $bytes = (string) substr( $bytes, $frame ); } } return $bytes; } /** * Length in bytes of the MPEG audio Layer III frame starting at $pos, or 0 when * there is no valid frame header there. * * @param string $bytes Data. * @param int $pos Offset. * @return int */ public static function mp3_frame_length( $bytes, $pos ) { if ( strlen( $bytes ) < $pos + 4 ) { return 0; } $b0 = ord( $bytes[$pos] ); $b1 = ord( $bytes[$pos + 1] ); $b2 = ord( $bytes[$pos + 2] ); if ( 0xff !== $b0 || 0xe0 !== ($b1 & 0xe0) ) { return 0; } $version = $b1 >> 3 & 3; // 3 MPEG-1, 2 MPEG-2, 0 MPEG-2.5. $layer = $b1 >> 1 & 3; // 1 is Layer III. $br_idx = $b2 >> 4 & 0xf; $sr_idx = $b2 >> 2 & 3; $padding = $b2 >> 1 & 1; if ( 1 === $version || 1 !== $layer || 0 === $br_idx || 15 === $br_idx || 3 === $sr_idx ) { return 0; } $mpeg1 = 3 === $version; $bitrates = ( $mpeg1 ? array( 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 ) : array( 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 ) ); $rates = array( 3 => array(44100, 48000, 32000), 2 => array(22050, 24000, 16000), 0 => array(11025, 12000, 8000), ); $bitrate = $bitrates[$br_idx] * 1000; $rate = $rates[$version][$sr_idx]; return (int) floor( (( $mpeg1 ? 144 : 72 )) * $bitrate / $rate ) + $padding; } /** * Length of plain MPEG frames in seconds, counted frame by frame. * * @param string $bytes Frames. * @return float */ public static function mp3_duration( $bytes ) { $len = strlen( $bytes ); $pos = 0; $seconds = 0.0; while ( $pos + 4 <= $len ) { $frame = self::mp3_frame_length( $bytes, $pos ); if ( 0 === $frame ) { break; } $b1 = ord( $bytes[$pos + 1] ); $version = $b1 >> 3 & 3; $sr_idx = ord( $bytes[$pos + 2] ) >> 2 & 3; $rates = array( 3 => array(44100, 48000, 32000), 2 => array(22050, 24000, 16000), 0 => array(11025, 12000, 8000), ); $samples = ( 3 === $version ? 1152 : 576 ); $seconds += $samples / $rates[$version][$sr_idx]; $pos += $frame; } if ( $seconds <= 0 ) { $seconds = $len * 8 / self::MP3_BITRATE; } return $seconds; } /** * Samples and format from a WAV file, or false when the bytes are not WAV. * * @param string $bytes Data. * @return array|false pcm, rate, channels, bits. */ public static function parse_wav( $bytes ) { $len = strlen( $bytes ); if ( $len < 44 || 'RIFF' !== substr( $bytes, 0, 4 ) || 'WAVE' !== substr( $bytes, 8, 4 ) ) { return false; } $pos = 12; $fmt = null; while ( $pos + 8 <= $len ) { $id = substr( $bytes, $pos, 4 ); $size = unpack( 'V', substr( $bytes, $pos + 4, 4 ) ); $size = (int) $size[1]; if ( 'fmt ' === $id && $size >= 16 ) { $fmt = unpack( 'vformat/vchannels/Vrate/Vbyterate/vblock/vbits', substr( $bytes, $pos + 8, 16 ) ); } elseif ( 'data' === $id ) { if ( !$fmt ) { return false; } $available = $len - ($pos + 8); $size = ( $size <= 0 || $size > $available ? $available : $size ); return array( 'pcm' => (string) substr( $bytes, $pos + 8, $size ), 'rate' => max( 1, (int) $fmt['rate'] ), 'channels' => max( 1, (int) $fmt['channels'] ), 'bits' => max( 8, (int) $fmt['bits'] ), ); } $pos += 8 + $size + ($size & 1); } return false; } /** * Header for a PCM WAV file. * * @param int $data_len Bytes of samples. * @param int $rate Sample rate. * @param int $channels Channels. * @param int $bits Bits per sample. * @return string */ public static function wav_header( $data_len, $rate, $channels = 1, $bits = 16 ) { $block = (int) ($channels * $bits / 8); return 'RIFF' . pack( 'V', 36 + $data_len ) . 'WAVE' . 'fmt ' . pack( 'VvvVVvv', 16, 1, $channels, $rate, $rate * $block, $block, $bits ) . 'data' . pack( 'V', $data_len ); } // ------------------------------------------------------------------ // Temporary parts // ------------------------------------------------------------------ /** * Base folder for parts in progress. * * @return string */ public static function tmp_base() { $uploads = wp_upload_dir( null, false ); return trailingslashit( $uploads['basedir'] ) . self::TMP_DIR; } /** * Folder for one job's parts. * * @param int $post_id Post ID. * @param string $job_id Job id. * @return string */ private function job_dir( $post_id, $job_id ) { return self::tmp_base() . '/' . (int) $post_id . '-' . preg_replace( '/[^a-z0-9]/', '', strtolower( (string) $job_id ) ); } /** * Keep the parts folder out of directory listings. * * @param string $dir Folder. */ private static function protect_dir( $dir ) { if ( is_dir( $dir ) && !file_exists( $dir . '/index.php' ) ) { file_put_contents( $dir . '/index.php', "rmdir( $dir, true ); } /** * Schedules the daily cleanup of unfinished parts, once. */ public static function schedule_cleanup() { if ( !wp_next_scheduled( self::CLEANUP_HOOK ) ) { wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::CLEANUP_HOOK ); } } /** * Removes parts of recordings that nobody carried on with for longer than JOB_TTL * (daily event). Recordings in progress are left alone. */ public static function cleanup_stale() { $base = self::tmp_base(); $dirs = glob( $base . '/*', GLOB_ONLYDIR ); $cutoff = time() - self::JOB_TTL; foreach ( ( is_array( $dirs ) ? $dirs : array() ) as $dir ) { $changed = filemtime( $dir ); if ( false !== $changed && $changed < $cutoff ) { self::remove_dir( $dir ); } } $left = glob( $base . '/*', GLOB_ONLYDIR ); if ( is_dir( $base ) && empty( $left ) ) { self::remove_dir( $base ); } } /** * Remove every unfinished part on the site (plugin deactivation). */ public static function cleanup_all() { $base = self::tmp_base(); $dirs = glob( $base . '/*', GLOB_ONLYDIR ); foreach ( ( is_array( $dirs ) ? $dirs : array() ) as $dir ) { self::remove_dir( $dir ); } self::remove_dir( $base ); } // ------------------------------------------------------------------ // Front end // ------------------------------------------------------------------ /** * Recording to show on the current single post, or 0. * * @param int $post_id Post ID. * @return int Attachment ID. */ private function player_attachment( $post_id ) { $post = get_post( $post_id ); if ( !$post || post_password_required( $post ) ) { return 0; } $cfg = $this->config(); if ( !$cfg['enabled'] || !in_array( $post->post_type, $cfg['post_types'], true ) ) { return 0; } if ( '1' === (string) get_post_meta( $post->ID, self::META_HIDDEN, true ) ) { return 0; } return $this->attachment_id( $post->ID ); } /** * Put the player above the content of a single post that has a recording. * * @param string $content Post content. * @return string */ public function render_player( $content ) { if ( !is_singular() || !in_the_loop() || !is_main_query() || is_feed() ) { return $content; } $post_id = get_the_ID(); if ( !$post_id || (int) get_queried_object_id() !== (int) $post_id ) { return $content; } $att = $this->player_attachment( $post_id ); if ( !$att || self::building_excerpt() ) { return $content; } $url = wp_get_attachment_url( $att ); if ( !$url ) { return $content; } $cfg = $this->config(); $seconds = (int) get_post_meta( $post_id, self::META_SECONDS, true ); $mime = (string) get_post_mime_type( $att ); $html = '
' . '

' . '' . esc_html( $cfg['label'] ) . '' . (( $seconds > 0 ? ' ' . esc_html( self::format_duration( $seconds ) ) . '' : '' )) . '

' . '' . '
'; /** * Filters the "Listen to this post" player markup. * * @param string $html Player HTML. * @param int $attachment_id Audio attachment ID. * @param int $post_id Post ID. */ $html = apply_filters( 'aifi_audio_player_html', $html, $att, $post_id ); return $html . $content; } /** * Whether the_content is running to build an excerpt (a meta description, a related * posts box), where the player's words would end up in the summary text. * * @return bool */ private static function building_excerpt() { if ( doing_filter( 'get_the_excerpt' ) || doing_filter( 'wp_trim_excerpt' ) ) { return true; } // wp_trim_excerpt() called directly, outside get_the_excerpt. foreach ( debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 15 ) as $frame ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace if ( isset( $frame['function'] ) && 'wp_trim_excerpt' === $frame['function'] && empty( $frame['class'] ) ) { return true; } } return false; } /** * Load the player styles only where a player is shown. */ public function enqueue_front() { if ( !is_singular() ) { return; } if ( !$this->player_attachment( get_queried_object_id() ) ) { return; } wp_enqueue_style( 'aifi-audio', AIFI_PLUGIN_URL . 'assets/css/audio-front.css', array(), AIFI_VERSION ); } }