'af', 'name' => 'Afrikaans', ), array( 'code' => 'sq', 'name' => 'Albanian', ), array( 'code' => 'am', 'name' => 'Amharic', ), array( 'code' => 'ar', 'name' => 'Arabic', ), array( 'code' => 'az', 'name' => 'Azerbaijani', ), array( 'code' => 'bn', 'name' => 'Bengali', ), array( 'code' => 'bs', 'name' => 'Bosnian', ), array( 'code' => 'bg', 'name' => 'Bulgarian', ), array( 'code' => 'fr-CA', 'name' => 'Canadian French', ), array( 'code' => 'ca', 'name' => 'Catalan', ), array( 'code' => 'da', 'name' => 'Danish', ), array( 'code' => 'nl', 'name' => 'Dutch', ), array( 'code' => 'zh', 'name' => 'Chinese', ), array( 'code' => 'hr', 'name' => 'Croatian', ), array( 'code' => 'cs', 'name' => 'Czech', ), array( 'code' => 'fa-AF', 'name' => 'Dari', ), array( 'code' => 'en', 'name' => 'English', ), array( 'code' => 'et', 'name' => 'Estonian', ), array( 'code' => 'fi', 'name' => 'Finish', ), array( 'code' => 'fr', 'name' => 'French', ), array( 'code' => 'ka', 'name' => 'Georgian', ), array( 'code' => 'de', 'name' => 'German', ), array( 'code' => 'el', 'name' => 'Greek', ), array( 'code' => 'ha', 'name' => 'Hausa', ), array( 'code' => 'he', 'name' => 'Hebrew', ), array( 'code' => 'hi', 'name' => 'Hindi', ), array( 'code' => 'hu', 'name' => 'Hungarian', ), array( 'code' => 'is', 'name' => 'Icelandic', ), array( 'code' => 'it', 'name' => 'Italian', ), array( 'code' => 'id', 'name' => 'Indonesian', ), array( 'code' => 'ja', 'name' => 'Japanese', ), array( 'code' => 'ko', 'name' => 'Korean', ), array( 'code' => 'lv', 'name' => 'Latvian', ), array( 'code' => 'ms', 'name' => 'Malay', ), array( 'code' => 'no', 'name' => 'Norwegian', ), array( 'code' => 'fa', 'name' => 'Persian', ), array( 'code' => 'pl', 'name' => 'Polish', ), array( 'code' => 'pt', 'name' => 'Portuguese', ), array( 'code' => 'ps', 'name' => 'Pushto', ), array( 'code' => 'ro', 'name' => 'Romanian', ), array( 'code' => 'sr', 'name' => 'Serbian', ), array( 'code' => 'sk', 'name' => 'Slovak', ), array( 'code' => 'sl', 'name' => 'Slovenian', ), array( 'code' => 'so', 'name' => 'Somali', ), array( 'code' => 'sw', 'name' => 'Swahili', ), array( 'code' => 'ru', 'name' => 'Russian', ), array( 'code' => 'es', 'name' => 'Spanish', ), array( 'code' => 'sv', 'name' => 'Swedish', ), array( 'code' => 'tl', 'name' => 'Tagalog', ), array( 'code' => 'ta', 'name' => 'Tamil', ), array( 'code' => 'th', 'name' => 'Thai', ), array( 'code' => 'tr', 'name' => 'Turkish', ), array( 'code' => 'uk', 'name' => 'Ukrainian', ), array( 'code' => 'ur', 'name' => 'Urdu', ), array( 'code' => 'vi', 'name' => 'Vietnamese', ), array( 'code' => 'cy', 'name' => 'Welsh', ), ); private $sdk; private $polly_client; private $s3_handler; private $local_file_handler; private $audio_storage; private $logger; /** * Creates SDK objects for the plugin. * * @since 0.1 */ public function __construct() { $this->logger = new Logger(); } public function prepare_paragraphs( $post_id) { $clean_content = ''; $post_content = get_post_field( 'post_content', $post_id ); $paragraphs = explode( "\n", $post_content ); foreach ($paragraphs as $paragraph) { $clean_paragraph = $this->clean_paragraph( $paragraph ); $clean_content = $clean_content . "\n" . $clean_paragraph; } return $clean_content; } public function clean_paragraph( $paragraph) { $clean_text = $paragraph; $clean_text = do_shortcode( $clean_text ); $clean_text = str_replace( ' ', ' ', $clean_text ); $is_ssml_enabled = $this->is_ssml_enabled(); if ($is_ssml_enabled) { $clean_text = $this->encode_ssml_tags( $clean_text ); } $clean_text = strip_tags( $clean_text, '' ); $clean_text = esc_html( $clean_text ); $clean_text = str_replace( ' ', ' ', $clean_text ); $clean_text = preg_replace( '/https:\/\/([^\s]+)/', '', $clean_text ); $clean_text = html_entity_decode( $clean_text, ENT_QUOTES, 'UTF-8' ); $clean_text = str_replace( '&', ' and ', $clean_text ); $clean_text = str_replace( '<', ' ', $clean_text ); $clean_text = str_replace( '>', ' ', $clean_text ); return $clean_text; } public function get_language_name( $provided_langauge_code) { foreach ($this->languages as $language_data) { $language_code = $language_data['code']; $language_name = $language_data['name']; if ($language_code === $provided_langauge_code) { return $language_name; } } return 'N/A'; } public function get_all_languages() { $supported_languages = array(); foreach ($this->languages as $language_data) { $language_code = $language_data['code']; array_push( $supported_languages, $language_code ); } return $supported_languages; } private function get_polly_voices_transient_key() { return self::POLLY_VOICES_TRANSIENT_PREFIX . md5( (string) $this->get_aws_region() ); } public function get_audio_state_meta_key(): string { return self::AUDIO_STATE_META_KEY; } public function get_valid_audio_states(): array { return array( self::AUDIO_STATE_NONE, self::AUDIO_STATE_QUEUED, self::AUDIO_STATE_RUNNING, self::AUDIO_STATE_READY, self::AUDIO_STATE_ERROR, ); } public function normalize_audio_state( $state ): string { $state = sanitize_key( (string) $state ); return in_array( $state, $this->get_valid_audio_states(), true ) ? $state : self::AUDIO_STATE_NONE; } public function get_persisted_post_audio_state( int $post_id ): string { $state = sanitize_key( (string) get_post_meta( $post_id, self::AUDIO_STATE_META_KEY, true ) ); return in_array( $state, $this->get_valid_audio_states(), true ) ? $state : ''; } public function has_post_audio( int $post_id ): bool { return '' !== trim( (string) get_post_meta( $post_id, 'itron_polly_tts_audio_link_location', true ) ); } public function get_post_audio_state( int $post_id ): string { $state = $this->get_persisted_post_audio_state( $post_id ); if ( '' !== $state ) { return $state; } return $this->has_post_audio( $post_id ) ? self::AUDIO_STATE_READY : ''; } public function set_post_audio_state( int $post_id, string $state ): void { update_post_meta( $post_id, self::AUDIO_STATE_META_KEY, $this->normalize_audio_state( $state ) ); clean_post_cache( $post_id ); } public function backfill_legacy_audio_states() { global $wpdb; $post_types = array_values( array_filter( $this->get_posttypes_array(), 'is_string' ) ); if ( array() === $post_types ) { return 0; } $post_type_placeholders = implode( ', ', array_fill( 0, count( $post_types ), '%s' ) ); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber,WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Intentional single backfill query over dynamic post types with a dynamic IN() placeholder list. $inserted_rows = $wpdb->query( $wpdb->prepare( "INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) SELECT p.ID, %s, CASE WHEN EXISTS ( SELECT 1 FROM {$wpdb->postmeta} AS audio_meta WHERE audio_meta.post_id = p.ID AND audio_meta.meta_key = %s AND audio_meta.meta_value <> '' ) THEN %s ELSE %s END FROM {$wpdb->posts} AS p LEFT JOIN {$wpdb->postmeta} AS state_meta ON state_meta.post_id = p.ID AND state_meta.meta_key = %s WHERE p.post_type IN ({$post_type_placeholders}) AND p.post_status NOT IN ('auto-draft', 'trash', 'inherit') AND state_meta.meta_id IS NULL", self::AUDIO_STATE_META_KEY, 'itron_polly_tts_audio_link_location', self::AUDIO_STATE_READY, self::AUDIO_STATE_NONE, self::AUDIO_STATE_META_KEY, ...$post_types ) ); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber,WordPress.DB.PreparedSQL.InterpolatedNotPrepared if ( false === $inserted_rows ) { return false; } if ( function_exists( 'wp_cache_set_posts_last_changed' ) ) { wp_cache_set_posts_last_changed(); } return (int) $inserted_rows; } private function sort_polly_voices_list( array &$voices ) { usort( $voices, static function ( $voice1, $voice2 ) { $label1 = sprintf( '%s %s', $voice1['LanguageName'] ?? '', $voice1['Id'] ?? '' ); $label2 = sprintf( '%s %s', $voice2['LanguageName'] ?? '', $voice2['Id'] ?? '' ); return strcmp( $label1, $label2 ); } ); } private function fetch_polly_voices_from_api() { $voices = array(); $args = array( 'IncludeAdditionalLanguageCodes' => true, ); $next_token = null; do { if ( $next_token ) { $args['NextToken'] = $next_token; } else { unset( $args['NextToken'] ); } $result = $this->polly_client->describeVoices( $args ); $result_voices = $result['Voices'] ?? array(); if ( is_array( $result_voices ) ) { $voices = array_merge( $voices, $result_voices ); } $next_token = $result['NextToken'] ?? null; } while ( ! empty( $next_token ) ); $this->sort_polly_voices_list( $voices ); return array( 'Voices' => $voices, ); } private function get_language_match_data( $language_code ) { $language_code = strtolower( (string) $language_code ); $primary_language = strtok( $language_code, '-' ); $match_data = array( 'exact' => array(), 'roots' => array(), ); if ( ! empty( $language_code ) ) { $match_data['exact'][] = $language_code; } if ( ! empty( $primary_language ) && false === strpos( $language_code, '-' ) ) { $match_data['roots'][] = $primary_language; } $aliases = array( 'ar' => array( 'exact' => array( 'arb' ), 'roots' => array( 'arb' ), ), 'no' => array( 'exact' => array( 'nb-no' ), 'roots' => array( 'nb' ), ), 'zh' => array( 'exact' => array( 'cmn-cn', 'yue-cn' ), 'roots' => array( 'cmn', 'yue' ), ), ); if ( isset( $aliases[ $language_code ] ) ) { $match_data['exact'] = array_merge( $match_data['exact'], $aliases[ $language_code ]['exact'] ); $match_data['roots'] = array_merge( $match_data['roots'], $aliases[ $language_code ]['roots'] ); } $match_data['exact'] = array_values( array_unique( array_filter( $match_data['exact'] ) ) ); $match_data['roots'] = array_values( array_unique( array_filter( $match_data['roots'] ) ) ); return $match_data; } private function is_polly_language_code_match( $voice_language_code, array $match_data ) { $voice_language_code = strtolower( (string) $voice_language_code ); $voice_language_root = strtok( $voice_language_code, '-' ); if ( in_array( $voice_language_code, $match_data['exact'], true ) ) { return true; } return in_array( $voice_language_root, $match_data['roots'], true ); } private function voice_matches_language( array $voice, $language_code ) { $match_data = $this->get_language_match_data( $language_code ); $voice_language_codes = array(); if ( ! empty( $voice['LanguageCode'] ) ) { $voice_language_codes[] = $voice['LanguageCode']; } if ( ! empty( $voice['AdditionalLanguageCodes'] ) && is_array( $voice['AdditionalLanguageCodes'] ) ) { $voice_language_codes = array_merge( $voice_language_codes, $voice['AdditionalLanguageCodes'] ); } foreach ( $voice_language_codes as $voice_language_code ) { if ( $this->is_polly_language_code_match( $voice_language_code, $match_data ) ) { return true; } } return false; } private function get_supported_synthesis_engines( array $voice ) { $supported_engines = $voice['SupportedEngines'] ?? array( 'standard' ); if ( ! is_array( $supported_engines ) ) { $supported_engines = array( 'standard' ); } $supported_engines = array_values( array_intersect( $supported_engines, array( 'standard', 'neural' ) ) ); if ( empty( $supported_engines ) && empty( $voice['SupportedEngines'] ) ) { $supported_engines = array( 'standard' ); } return $supported_engines; } public function is_standard_supported_for_voice( $voice ) { $voice_data = is_array( $voice ) ? $voice : $this->get_polly_voice( $voice ); if ( is_array( $voice_data ) ) { return in_array( 'standard', $this->get_supported_synthesis_engines( $voice_data ), true ); } return false; } public function get_polly_voice_capability( $voice ) { $voice_data = is_array( $voice ) ? $voice : $this->get_polly_voice( $voice ); if ( is_array( $voice_data ) ) { $supported_engines = $this->get_supported_synthesis_engines( $voice_data ); if ( in_array( 'standard', $supported_engines, true ) && in_array( 'neural', $supported_engines, true ) ) { return 'standard_neural'; } if ( in_array( 'neural', $supported_engines, true ) ) { return 'neural_only'; } } return 'standard'; } public function get_polly_voice_capability_label( $voice ) { switch ( $this->get_polly_voice_capability( $voice ) ) { case 'standard_neural': return 'Standard + Neural'; case 'neural_only': return 'Neural only'; default: return 'Standard'; } } public function is_polly_neural_requested() { return ! empty( get_option( 'itron_polly_tts_neural', '' ) ); } public function is_voice_compatible_with_neural_setting( $voice, $neural_requested = null ) { if ( null === $neural_requested ) { $neural_requested = $this->is_polly_neural_requested(); } if ( $neural_requested ) { return true; } return $this->is_standard_supported_for_voice( $voice ); } public function get_available_polly_voices( $language_code = null ) { if ( empty( $language_code ) ) { $language_code = $this->get_source_language(); } $voices = $this->get_polly_voices(); $available_voices = array(); foreach ( $voices['Voices'] ?? array() as $voice ) { if ( ! $this->voice_matches_language( $voice, $language_code ) ) { continue; } if ( empty( $this->get_supported_synthesis_engines( $voice ) ) ) { continue; } $available_voices[] = $voice; } $this->sort_polly_voices_list( $available_voices ); return $available_voices; } public function get_compatible_polly_voices( $language_code = null, $neural_requested = null ) { $compatible_voices = array(); foreach ( $this->get_available_polly_voices( $language_code ) as $voice ) { if ( ! $this->is_voice_compatible_with_neural_setting( $voice, $neural_requested ) ) { continue; } $compatible_voices[] = $voice; } return $compatible_voices; } public function get_grouped_polly_voices( $language_code = null ) { $groups = array( 'standard' => array( 'label' => 'Standard Voices', 'voices' => array(), ), 'standard_neural' => array( 'label' => 'Standard + Neural Voices', 'voices' => array(), ), 'neural_only' => array( 'label' => 'Neural-only Voices', 'voices' => array(), ), ); foreach ( $this->get_available_polly_voices( $language_code ) as $voice ) { $groups[ $this->get_polly_voice_capability( $voice ) ]['voices'][] = $voice; } return $groups; } public function get_polly_voice( $voice_id ) { try { foreach ( $this->get_polly_voices()['Voices'] ?? array() as $voice ) { if ( ! empty( $voice['Id'] ) && $voice['Id'] === $voice_id ) { return $voice; } } } catch ( \Exception $e ) { return null; } return null; } public function resolve_polly_voice_id( $language_code, $requested_voice_id = '', $fallback_voice_id = '', array $args = array() ) { $neural_requested = $args['neural_requested'] ?? $this->is_polly_neural_requested(); $available_voices = $this->get_compatible_polly_voices( $language_code, $neural_requested ); if ( empty( $available_voices ) ) { return ''; } $available_voice_ids = array_column( $available_voices, 'Id' ); foreach ( array( $requested_voice_id, $fallback_voice_id ) as $candidate_voice_id ) { $candidate_voice_id = (string) $candidate_voice_id; if ( ! empty( $candidate_voice_id ) && in_array( $candidate_voice_id, $available_voice_ids, true ) ) { return $candidate_voice_id; } } return (string) $available_voices[0]['Id']; } public function get_resolved_polly_voice_option( $option_name, $language_code, $fallback_voice_id = '', array $args = array() ) { $current_voice_id = array_key_exists( 'requested_voice_id', $args ) ? (string) $args['requested_voice_id'] : (string) get_option( $option_name, '' ); return $this->resolve_polly_voice_id( $language_code, $current_voice_id, $fallback_voice_id, $args ); } public function sync_polly_voice_option( $option_name, $language_code, $fallback_voice_id = '', array $args = array() ) { $current_voice_id = (string) get_option( $option_name, '' ); $resolved_voice_id = $this->get_resolved_polly_voice_option( $option_name, $language_code, $fallback_voice_id, $args ); if ( $resolved_voice_id !== $current_voice_id ) { if ( '' === $resolved_voice_id ) { delete_option( $option_name ); } else { update_option( $option_name, $resolved_voice_id ); } } return $resolved_voice_id; } public function get_source_language_name() { $selected_source_language = $this->get_source_language(); foreach ($this->languages as $language_data) { $language = $language_data['code']; if (strcmp( $selected_source_language, $language ) === 0) { return $language_data['name']; } } return ''; } public function init() { $audio_storage = $this->get_audio_storage(); $aws_sdk_config = $this->get_aws_sdk_config(); $this->sdk = new \Aws\Sdk( $aws_sdk_config ); $this->polly_client = $this->sdk->createPolly(); $this->s3_handler = new S3FileHandler( $this, $audio_storage ); $this->local_file_handler = new LocalFileHandler( $this, $audio_storage ); $this->s3_handler->set_s3_client( $this->sdk->createS3() ); } /** * Method returns file handler which is reponsible for communicating with proper storage location. * * @since 0.1 */ public function get_file_handler() { $is_s3_enabled = $this->is_s3_enabled(); if ( $is_s3_enabled ) { return $this->s3_handler; } else { return $this->local_file_handler; } } public function get_polly_client() { return $this->polly_client; } public function get_audio_storage(): AudioStorage { if ( ! $this->audio_storage instanceof AudioStorage ) { $this->audio_storage = new AudioStorage(); $this->audio_storage->register_hooks(); } return $this->audio_storage; } /** * Create an S3 client with current credentials for an asset's original region. */ public function get_s3_client_for_region( string $region ) { if ( ! $this->has_aws_credentials() ) { throw new CredentialsException( 'AWS credentials are required to remove the original audio object.' ); } $sdk = new \Aws\Sdk( $this->get_aws_sdk_config( $region ) ); return $sdk->createS3(); } /** * Method removes ID3 tag from audio file * * @param string $filename File for which tag should be removed. * @since 0.1 */ public function remove_id3( $filename, $wp_filesystem = null ) { if ( null === $wp_filesystem ) { $wp_filesystem = $this->prepare_wp_filesystem(); } if ( ! is_object( $wp_filesystem ) || ! $wp_filesystem->exists( $filename ) ) { return; } $contents = $wp_filesystem->get_contents( $filename ); if ( ! is_string( $contents ) || strlen( $contents ) < 10 ) { return; } $id3_header = substr( $contents, 0, 10 ); if ( 'ID3' !== substr( $id3_header, 0, 3 ) ) { return; } // Calculating the total size of IDv3 tag. $int_value = 0; $byte_word = substr( $id3_header, 6, 4 ); $byte_word_length = strlen( $byte_word ); for ( $i = 0; $i < $byte_word_length; $i++ ) { $int_value += ( ord( $byte_word[ $i ] ) & 0x7F ) * pow( 2, ( $byte_word_length - 1 - $i ) * 7 ); } $offset = ( (int) $int_value ) + 10; if ( $offset >= strlen( $contents ) ) { return; } $trimmed_audio = substr( $contents, $offset ); if ( ! $wp_filesystem->put_contents( $filename, $trimmed_audio ) ) { throw new \RuntimeException( 'Could not rewrite the temporary audio part without its ID3 header.' ); } } /** * Checks if auto breaths are enabled. * * @since 0.1 */ public function is_auto_breaths_enabled() { //If Neural TTS is enabled breaths SSML tags are not supported. $neural_enabled = $this->is_polly_neural_enabled(); if ($neural_enabled) { return false; } $value = get_option( 'itron_polly_tts_auto_breaths', 'on' ); if ( empty( $value ) ) { $result = false; } else { $result = true; } return $result; } /** * Returns source language. * * @since 0.1 */ public function get_post_source_language( $post_id) { $value = get_post_meta( $post_id, 'itron_polly_tts_source_language', true ); if (empty( $value )) { $value = $this->get_source_language(); } return $value; } /** * Returns source language. * * @since 0.1 */ public function get_source_language() { $value = get_option( 'itron_polly_tts_source_language', 'en' ); if (empty( $value )) { $value = 'en'; } return $value; } public function replace_if_empty( $value, $new_value) { if ( ! empty( $value )) { return $value; } else { return $new_value; } } public function is_polly_enabled_for_new_posts() { if ( $this->is_polly_enabled() ) { $default_configuration = get_option( 'itron_polly_tts_defconf' ); if ( 'Amazon Polly enabled' === $default_configuration ) { return true; } else { return false; } } } public function is_audio_download_enabled() { $value = $this->checked_validator( 'itron_polly_tts_download_enabled' ); if ('checked' == trim( $value )) { return true; } else { return false; } } /** * Validates if logging is enabled. * * @since 0.1 */ public function is_logging_enabled( $enabled = true ): bool { return (bool) $enabled && ! empty( get_option( 'itron_polly_tts_logging', false ) ); } /** * Validates if Amazon Polly support is enabled. * * @since 0.1 */ public function is_polly_enabled() { return ! empty( get_option( 'itron_polly_tts_polly_enable', '' ) ); } public function has_aws_credentials(): bool { return ! empty( $this->get_aws_sdk_config()['credentials'] ); } /** * Validates if AWS configuration is correct and AWS can be reached. * * @since 0.1 * @return bool */ public function validate_itron_polly_tts_access( $persist_state = true, $show_notices = true ): bool { if ( ! $this->is_polly_enabled() || ! $this->has_aws_credentials() ) { return false; } try { if ( ! $this->check_aws_access( $persist_state ) ) { return false; } if ( $this->is_s3_enabled() && ! $this->s3_handler->is_bucket_accessible() ) { throw new S3BucketNotAccessibleException( 'Configure an accessible S3 bucket.' ); } } catch (S3BucketNotAccessibleException $e) { if ( $show_notices ) { $this->show_error_notice( 'notice-info', "The S3 bucket doesn't exist or can't be accessed." ); } return false; } catch (CredentialsException $e) { if ( $show_notices ) { $this->show_error_notice( 'notice-error', "Can't connect to AWS. Check your AWS credentials." ); } return false; } catch (\Exception $e) { if ( $show_notices ) { $this->show_error_notice( 'notice-error', 'AWS could not be reached. Check the region, credentials, service permissions and server connectivity.' ); } return false; } return true; } public function show_error_notice( $type, $message) { add_action( 'admin_notices', function () use ( $type, $message ) { printf( '

%2$s

', esc_attr( $type ), esc_html( $message ) ); } ); } public function normalize_sample_rate( $sample_rate ) { $sample_rate = (string) $sample_rate; if ( ! in_array( $sample_rate, array( '24000', '22050', '16000', '8000' ), true ) ) { return '24000'; } return $sample_rate; } public function normalize_posttypes( $posttypes ) { if ( is_array( $posttypes ) ) { $posttypes = implode( ' ', $posttypes ); } $posttypes = str_replace( ',', ' ', (string) $posttypes ); $posttypes = preg_replace( '!\s+!', ' ', $posttypes ); $posttypes = trim( (string) $posttypes ); $posttypes = array_map( 'sanitize_key', array_filter( explode( ' ', $posttypes ) ) ); $posttypes = array_values( array_filter( $posttypes ) ); if ( empty( $posttypes ) ) { $posttypes = array( 'post' ); } return implode( ' ', $posttypes ); } public function normalize_audio_speed( $speed ) { $speed = trim( (string) $speed ); if ( '' === $speed ) { $speed = '100'; } $speed = (string) max( 20, min( 200, (int) $speed ) ); return $speed; } public function get_sample_rate() { $sample_rate = $this->normalize_sample_rate( get_option( 'itron_polly_tts_sample_rate' ) ); $this->logger->log( sprintf( '%s Sample rate: %s ', __METHOD__, $sample_rate ) ); return $sample_rate; } public function get_voice_id() { $voice_id = (string) get_option( 'itron_polly_tts_voice_id' ); if ( empty( $voice_id ) ) { $voice_id = 'Matthew'; } return $voice_id; } public function is_post_voice_override_disabled() { return ! empty( get_option( 'itron_polly_tts_disable_post_voice_override', '' ) ); } public function is_post_voice_override_disabled_checked() { return $this->is_post_voice_override_disabled() ? ' checked ' : ''; } /** * @todo Move to GeneralConfiguration * Returns the name of the AWS region, which should be used by the plugin. * * @since 0.1 */ public function get_aws_region() { return GeneralConfiguration::get_aws_region(); } public function get_polly_voices( $force_refresh = false ) { if ( ! $this->is_polly_enabled() || ! $this->has_aws_credentials() ) { return array( 'Voices' => array() ); } $transient_key = $this->get_polly_voices_transient_key(); if ( ! $force_refresh ) { $voices = get_transient( $transient_key ); if ( is_array( $voices ) && isset( $voices['Voices'] ) ) { return $voices; } } $voices = $this->fetch_polly_voices_from_api(); set_transient( $transient_key, $voices, self::POLLY_VOICES_TRANSIENT_TTL ); return $voices; } /** * Return post type value. * * @since 0.1 */ public function get_posttypes() { return $this->normalize_posttypes( get_option( 'itron_polly_tts_posttypes', 'post' ) ); } /** * Return speed for audio files. * * @since 0.1 */ public function get_audio_speed() { return $this->normalize_audio_speed( get_option( 'itron_polly_tts_speed' ) ); } /** * Method returns lexicons specified in plugin configuration. * * @since 0.1 */ public function get_lexicons() { $lexicons = get_option( 'itron_polly_tts_lexicons', '' ); $lexicons = trim( $lexicons ); return $lexicons; } /** * Check whether the optional public AWS Polly credit is enabled. * * @since 0.1 */ public function is_poweredby_enabled() { $poweredby = get_option( 'itron_polly_tts_poweredby', '' ); if (empty( $poweredby )) { $result = false; } else { $result = true; } return $result; } /** * Check if SSML is enabled. * * @since 0.1 */ public function is_ssml_enabled() { return ! empty( get_option( 'itron_polly_tts_ssml', 'on' ) ); } /** * Utility function which checks if checkbox for option input should be checked. * * @param string $option Name of the option which should be checked. * @since 0.1 */ public function checked_validator( $option) { $option_value = get_option( $option, 'on' ); if (empty( $option_value )) { return ''; } else { return ' checked '; } } public function is_polly_neural_enabled() { return $this->is_polly_neural_requested() ? ' checked ' : ''; } public function normalize_polly_speaking_style( $style ) { $style = (string) $style; if ( 'news' === $style ) { return $style; } return ''; } public function get_requested_polly_speaking_style() { return $this->normalize_polly_speaking_style( get_option( 'itron_polly_tts_speaking_style', '' ) ); } public function get_active_polly_speaking_style( $voice = null, $neural_requested = null ) { if ( null === $voice ) { $voice = $this->get_voice_id(); } if ( null === $neural_requested ) { $neural_requested = $this->is_polly_neural_requested(); } if ( ! $neural_requested ) { return ''; } $style = $this->get_requested_polly_speaking_style(); if ( 'news' === $style && $this->is_news_style_for_voice( $voice ) ) { return 'news'; } return ''; } public function should_news_style_be_used( $voice) { if ( ! $this->is_news_style_for_voice( $voice )) { return false; } if ( 'news' === $this->get_requested_polly_speaking_style() ) { $engine = $this->get_polly_engine( $voice ); if ('neural' == $engine) { return true; } return false; } return false; } public function is_neural_supported_in_region() { foreach ( $this->get_polly_voices()['Voices'] ?? array() as $voice ) { if ( in_array( 'neural', $this->get_supported_synthesis_engines( $voice ), true ) ) { return true; } } return false; } public function is_news_style_for_voice( $voice) { $supported_voices = array( 'Joanna', 'Matthew', 'Lupe', 'Amy' ); if (in_array( $voice, $supported_voices )) { return true; } else { return false; } } public function is_neural_supported_for_voice( $voice) { $voice_data = $this->get_polly_voice( $voice ); if ( is_array( $voice_data ) ) { return in_array( 'neural', $this->get_supported_synthesis_engines( $voice_data ), true ); } return false; } public function get_polly_engine( $voice) { if ( $this->is_polly_neural_requested() && $this->is_neural_supported_for_voice( $voice ) ) { return 'neural'; } if ( $this->is_standard_supported_for_voice( $voice ) ) { return 'standard'; } throw new \RuntimeException( 'The selected voice has no enabled supported engine in this AWS region.' ); } /** * Checks if Media Libary support is enabled. * * @since 0.1 */ public function is_medialibrary_enabled() { $value = get_option( 'itron_polly_tts_medialibrary_enabled' ); if (empty( $value )) { $result = false; } else { $result = true; } return $result; } /** * Checks if S3 storage is enabled. * * @since 0.1 */ public function is_s3_enabled() { $value = get_option( 'itron_polly_tts_s3', 'on' ); if (empty( $value )) { $result = false; } else { $result = true; } return $result; } /** * Check connectivity with AWS can be eastablished. * * @since 0.1 */ private function check_aws_access( $persist_state = true ) { try { $voice_list = $this->get_polly_voices(); if ( empty( $voice_list['Voices'] ) ) { throw new CredentialsException( 'No supported Polly voices were returned.' ); } if ( $persist_state ) { update_option( 'itron_polly_tts_valid_keys', '1' ); } return true; } catch (\Exception $e) { if ( $persist_state ) { update_option( 'itron_polly_tts_valid_keys', '0' ); } throw new CredentialsException( 'Could not connect to AWS. Check your AWS credentials.' ); } } /** * Returns AWS SDK configuration to allow connection with AWS account. * * @since 0.1 */ private function get_aws_sdk_config( $region = null) { $aws_sdk_config = array( 'region' => GeneralConfiguration::get_aws_region(), 'version' => 'latest', 'ua_append' => array( 'request-source/itron-polly-tts' ), ); $credentials = false; $aws_access_key = GeneralConfiguration::get_aws_access_key(); $aws_secret_key = GeneralConfiguration::get_aws_secret_key(); if ($aws_access_key && $aws_secret_key) { $credentials = array( 'key' => $aws_access_key, 'secret' => $aws_secret_key, ); } $credentials = apply_filters( 'itron_polly_tts_aws_sdk_credentials', $credentials ); if ( $credentials ) { $aws_sdk_config['credentials'] = $credentials; } if ($region) { $aws_sdk_config['region'] = $region; } return $aws_sdk_config; } /** * Method prepare WP_Filesystem variable for interacting with local file system. * * @since 0.1 */ public function prepare_wp_filesystem() { /** Ensure WordPress Administration File API is loaded as REST requests do not load the file API */ require_once( ABSPATH . 'wp-admin/includes/file.php' ); $url = wp_nonce_url( admin_url( 'post-new.php' ) ); $creds = request_filesystem_credentials( $url ); if ( ! WP_Filesystem( $creds ) ) { request_filesystem_credentials( $url ); return true; } global $wp_filesystem; return $wp_filesystem; } /** * Method breakes input text into smaller parts. * * @since 0.1 * @param string $text Text which should be broken. */ public function break_text( $text) { $parts = array(); if ( ! empty( $text )) { $part_id = 0; $paragraphs = explode( "\n", $text ); foreach ($paragraphs as $paragraph) { $paragraph_size = strlen( trim( $paragraph ) ); if ($paragraph_size > 0) { if ($paragraph_size <= 2800) { $parts[ $part_id ] = $paragraph . ' **AMAZONPOLLY*SSML*BREAK*time=***500ms***SSML** '; $part_id++; } else { $words = explode( ' ', $paragraph ); $current_part = ''; $last_part = ''; foreach ($words as $word) { $word_length = strlen( $word ); $current_part_length = strlen( $current_part ); if ($word_length + $current_part_length < 2800) { $current_part = $current_part . $word . ' '; $last_part = $current_part; } else { $current_part = $current_part . $word . ' '; $parts[ $part_id ] = $current_part; $part_id++; $current_part = ''; $last_part = ''; } } $parts[ $part_id ] = $last_part . ' **AMAZONPOLLY*SSML*BREAK*time=***500ms***SSML** '; $part_id++; } //end if } //end if } //end foreach } //end if return $parts; } public function modify_sentence_speed( $sentence) { $speed = $this->get_audio_speed(); if (100 !== $speed) { $sentence = '' . $sentence . ''; } return $sentence; } /** * Checks if post title should be added. * * @since 0.1 */ public function is_excerpt_adder_enabled() { $value = get_option( 'itron_polly_tts_add_post_excerpt', 'on' ); if (empty( $value )) { $result = false; } else { $result = true; } return $result; } /** * Encode SSML tags. * * @since 0.1 * @param string $text text which should be decoded. */ public function decode_ssml_tags( $text ) { $text = preg_replace( '/(\*\*AMAZONPOLLY\*SSML\*BREAK\*)(.*?)(\*\*\*)(.*?)(\*\*\*SSML\*\*)/', '', $text ); return $text; } public function get_audio_voice_request( int $post_id ): array { $voice_id = $this->is_post_voice_override_disabled() ? '' : (string) get_post_meta( $post_id, 'itron_polly_tts_voice_id', true ); if ( '' === $voice_id ) { $voice_id = $this->get_voice_id(); } return array( 'voice' => $voice_id, 'language' => $this->get_post_source_language( $post_id ), 'region' => $this->get_aws_region(), ); } public function get_audio_hash( $post_id, ?string $clean_text = null, ?string $resolved_voice_id = null ): string { $request = $this->get_audio_voice_request( (int) $post_id ); $stored = get_post_meta( $post_id, 'itron_polly_tts_audio_voice', true ); // Reuse the last resolution offline only while its requested inputs still match. $voice_id = $resolved_voice_id ?? ( is_array( $stored ) && ( $stored['request'] ?? null ) === $request ? (string) ( $stored['resolved'] ?? $request['voice'] ) : $request['voice'] ); // Fingerprint speech inputs without fetching the AWS voice catalog. $inputs = array( 'text' => $clean_text ?? $this->clean_text( $post_id, true, false ), 'language' => $this->get_post_source_language( $post_id ), 'voice' => $voice_id, 'region' => $this->get_aws_region(), 'sample_rate' => $this->normalize_sample_rate( get_option( 'itron_polly_tts_sample_rate' ) ), 'speed' => $this->get_audio_speed(), 'lexicons' => $this->get_lexicons(), 'neural' => $this->is_polly_neural_requested(), 'speaking_style' => $this->get_active_polly_speaking_style( $voice_id ), 'auto_breaths' => $this->is_auto_breaths_enabled(), 'ssml' => $this->is_ssml_enabled(), ); $encoded = wp_json_encode( $inputs ); if ( ! is_string( $encoded ) ) { throw new \RuntimeException( 'Unable to fingerprint speech inputs.' ); } return hash( 'sha256', $encoded ); } public function is_post_audio_current( int $post_id, ?string $current_hash = null ): bool { return $this->has_post_audio( $post_id ) && get_post_meta( $post_id, 'itron_polly_tts_audio_hash', true ) === ( $current_hash ?? $this->get_audio_hash( $post_id ) ); } /** * Method retrievies post which ID was provided, and clean it. * * @since 0.1 * @param string $post_id ID of the post for which test (content) should be prepapred for conversion. */ public function clean_text( $post_id, $with_title, $only_title) { #$this->logger->log(sprintf('%s Cleaning text (%s, %s) ', __METHOD__, $with_title, $only_title)); $clean_text = ''; // Depending on the plugin configurations, post's title will be added to the audio. if ($with_title) { if ($this->is_title_adder_enabled()) { // Omit request-dependent Protected/Private prefixes, but retain title filters. // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core WordPress title filter. $clean_text = apply_filters( 'the_title', get_post_field( 'post_title', $post_id ), $post_id ) . '. **AMAZONPOLLY*SSML*BREAK*time=***1s***SSML** '; } } // Depending on the plugin configurations, post's excerpt will be added to the audio. if ($this->is_excerpt_adder_enabled()) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core WordPress filter. $my_excerpt = apply_filters( 'the_excerpt', get_post_field( 'post_excerpt', $post_id ) ); $clean_text = $clean_text . $my_excerpt . ' **AMAZONPOLLY*SSML*BREAK*time=***1s***SSML** '; } $clean_text = $clean_text . get_post_field( 'post_content', $post_id ); $clean_text = apply_filters( 'itron_polly_tts_content', $clean_text ); if ($only_title) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Core WordPress title filter. $clean_text = apply_filters( 'the_title', get_post_field( 'post_title', $post_id ), $post_id ); } $clean_text = str_replace( ' ', ' ', $clean_text ); $clean_text = do_shortcode( $clean_text ); $clean_text = $this->skip_tags( $clean_text ); $clean_text = str_replace( array( '-AMAZONPOLLY-ONLYAUDIO-START-', '-AMAZONPOLLY-ONLYAUDIO-END-' ), '', $clean_text ); $clean_text = preg_replace( '/-AMAZONPOLLY-ONLYWORDS-START-[\S\s]*?-AMAZONPOLLY-ONLYWORDS-END-/', '', $clean_text ); $clean_text = $this->add_pauses( $clean_text ); $is_ssml_enabled = $this->is_ssml_enabled(); if ($is_ssml_enabled) { $clean_text = $this->encode_ssml_tags( $clean_text ); } // Creating text description for images $clean_text = $this->replace_images( $clean_text ); $clean_text = strip_tags( $clean_text, '' ); $clean_text = esc_html( $clean_text ); $clean_text = str_replace( ' ', ' ', $clean_text ); $clean_text = preg_replace( '/https:\/\/([^\s]+)/', '', $clean_text ); $clean_text_temp = ''; $paragraphs = explode( "\n", $clean_text ); foreach ($paragraphs as $paragraph) { $paragraph_size = strlen( trim( $paragraph ) ); if ($paragraph_size > 0) { $clean_text_temp = $clean_text_temp . "\n" . $paragraph; } } $clean_text = $clean_text_temp; $clean_text = html_entity_decode( $clean_text, ENT_QUOTES, 'UTF-8' ); $clean_text = str_replace( '&', ' and ', $clean_text ); $clean_text = str_replace( '<', ' ', $clean_text ); $clean_text = str_replace( '>', ' ', $clean_text ); return $clean_text; } private function replace_images( $clean_text) { //$new_clean_text = preg_replace('/]+>/', 'Image: $1.', $clean_text); $new_clean_text = preg_replace( '/]+>/', '$1', $clean_text ); return $new_clean_text; } /** * Run when deleting a post. * * @param string $post_id ID of the post which is gonna to be deleted. * @since 0.1 */ public function delete_post( $post_id ) { // Check if this isn't an auto save. if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; } if ( 'attachment' === get_post_type( $post_id ) ) { return; } $post_types_supported = $this->get_posttypes_array(); $post_type = get_post_type( $post_id ); if ( ! in_array( $post_type, $post_types_supported, true ) ) { return; } $this->delete_post_audio( $post_id ); } private function get_audio_state_meta_keys() { return array( AudioStorage::POST_META_KEY, 'itron_polly_tts_audio_link_location', 'itron_polly_tts_audio_location', 'itron_polly_tts_generated_voice_id', 'itron_polly_tts_audio_playtime', 'itron_polly_tts_audio_hash', 'itron_polly_tts_audio_voice', 'itron_polly_tts_media_library_attachment_id', 'itron_polly_tts_settings_hash', ); } private function get_file_handler_for_audio_descriptor( array $descriptor ) { $audio_storage = $this->get_audio_storage(); if ( 's3' === $descriptor['type'] ) { $handler = new S3FileHandler( $this, $audio_storage ); $handler->set_s3_client( $this->get_s3_client_for_region( $descriptor['region'] ) ); return $handler; } if ( 'local' === $descriptor['type'] ) { return new LocalFileHandler( $this, $audio_storage ); } throw new \InvalidArgumentException( 'Unsupported saved audio storage type.' ); } public function clear_post_audio_state_meta( int $post_id ): void { foreach ( $this->get_audio_state_meta_keys() as $meta_key ) { delete_post_meta( $post_id, $meta_key ); } } public function clear_post_audio_runtime_cache( int $post_id ): void { do_action( 'itron_polly_tts_clear_post_audio_runtime_cache', $post_id ); } public function clear_post_audio_state( int $post_id ): void { $this->clear_post_audio_state_meta( $post_id ); $this->set_post_audio_state( $post_id, self::AUDIO_STATE_NONE ); $this->clear_post_audio_runtime_cache( $post_id ); } /** * Delets audio for specific post. * * @param string $post_id ID of the post for which audio should be deleted. * @since 0.1 */ public function delete_post_audio( $post_id ) { $post_id = (int) $post_id; $audio_storage = $this->get_audio_storage(); $deleted = $audio_storage->cleanup_post_audio( $post_id, function ( array $descriptor ) use ( $post_id ) { $file_handler = $this->get_file_handler_for_audio_descriptor( $descriptor ); $wp_filesystem = 'local' === $descriptor['type'] ? $this->prepare_wp_filesystem() : null; return $file_handler->delete( $wp_filesystem, $descriptor, $post_id ); } ); $this->clear_post_audio_state( $post_id ); if ( ! $deleted ) { $this->logger->log( sprintf( '%s Audio cleanup failed for post id=%d; persistent recovery details were recorded.', __METHOD__, $post_id ) ); } return $deleted; } private function skip_tags( $text) { $skip_tags_array = $this->get_skiptags_array(); foreach ($skip_tags_array as $value) { $text = preg_replace( '/<' . $value . '>(\s*?)(.*?)(\s*?)<\/' . $value . '>/', '', $text ); } return $text; } private function add_pauses( $text) { #Creates a little pause after closes the tag
  • $text = str_replace( '
  • ', ' **AMAZONPOLLY*SSML*BREAK*time=***300ms***SSML** ', $text ); #Create a support to the tag (helpful to 'read' abreviations, for example) $text = preg_replace( '/]+|\s+))*>([\s\S]*?)<\/sub>/', '$2', $text ); return $text; } /** * Encode SSML tags. * * @since 0.1 * @param string $text text which should be encoded. */ private function encode_ssml_tags( $text) { $text = preg_replace( '//', '**AMAZONPOLLY*SSML*BREAK*$1***$2***SSML**', $text ); return $text; } /** * Checks if post title should be added. * * @since 0.1 */ public function is_title_adder_enabled() { $value = get_option( 'itron_polly_tts_add_post_title', 'on' ); if (empty( $value )) { $result = false; } else { $result = true; } return $result; } /** * Add an SSML QuickTag button for the classic editor. * * @since 0.1 */ public function add_quicktags() { if ( $this->is_ssml_enabled() && wp_script_is( 'quicktags' ) ) { wp_add_inline_script( 'quicktags', "QTags.addButton('itron_polly_tts_ssml_break', 'SSML Break', '', '', '', 'AWS Polly SSML Break Tag', 111);" ); } } /** * Configure supported HTML tags. * * @since 0.1 * @param string $tags supported tags. */ public function allowed_tags_tinymce( $tags ) { $ssml_tags = array( 'ssml', 'speak', 'break[time|whatever]', 'emphasis[level]', 'lang', 'mark', 'paragraph', 'phoneme', 'prosody', 's', 'say-as', 'sub', 'w', 'amazon:breath', 'amazon:auto-breaths', 'amazon:effect[name]', 'amazon:effect[phonation]', 'amazon:effect[vocal-tract-length]', 'amazon:effect[name]', ); $tags['extended_valid_elements'] = implode( ',', $ssml_tags ); return $tags; } /** * Configure supported HTML tags. * * @since 0.1 * @param string $tags supported tags. */ public function allowed_tags_kses( $tags ) { $tags['ssml'] = true; $tags['speak'] = true; $tags['break'] = array( 'time' => true, ); return $tags; } /** * Return skip tags array. * * @since 0.1 */ public function get_skiptags_array() { $array = get_option( 'itron_polly_tts_skip_tags' ); $array = explode( ' ', $array ); return $array; } /** * Return post type value array. * * @since 0.1 */ public function get_posttypes_array() { $posttypes_array = explode( ' ', $this->get_posttypes() ); $posttypes_array = array_values( array_filter( $posttypes_array ) ); $posttypes_array = apply_filters( 'itron_polly_tts_post_types', $posttypes_array ); return $posttypes_array; } /** * Register the stylesheets for the admin area. * * @since 0.1 */ private function get_asset_version( string $relative_path ): string { $asset_path = plugin_dir_path( dirname( __DIR__ ) . '/itron-polly-tts.php' ) . 'admin/' . ltrim( $relative_path, '/' ); if ( file_exists( $asset_path ) ) { return (string) filemtime( $asset_path ); } return ITRON_POLLY_TTS_VERSION; } public function enqueue_styles() { $admin_asset_url = plugin_dir_url( dirname( __DIR__ ) . '/itron-polly-tts.php' ) . 'admin/'; wp_enqueue_style( 'itron-polly-tts-admin', $admin_asset_url . 'css/itron-polly-tts-admin.css', array(), $this->get_asset_version( 'css/itron-polly-tts-admin.css' ), 'all' ); } /** * Register the JavaScript for the admin area. * * @since 0.1 */ public function enqueue_scripts() { $admin_asset_url = plugin_dir_url( dirname( __DIR__ ) . '/itron-polly-tts.php' ) . 'admin/'; wp_enqueue_script( 'itron-polly-tts-admin', $admin_asset_url . 'js/itron-polly-tts-admin.js', array( 'jquery' ), $this->get_asset_version( 'js/itron-polly-tts-admin.js' ), false ); } /** * Register meta box for 'Enable Amazon Polly' on post creation form. * * @since 0.1 */ public function field_checkbox() { $post_types_supported = $this->get_posttypes_array(); $meta_box = new PostMetaBox( $this ); add_meta_box( 'itron_polly_tts_box_id', // This is HTML id of the box on edit screen. 'Amazon Polly', // Title of the box. array( $meta_box, 'display_box_content' ), // Function to be called to display the checkboxes, see the function below. $post_types_supported, // On which edit screen the box should appear. 'normal', // Part of page where the box should appear. 'high' // Priority of the box. ); } public function add_settings_link( $links) { $settings_link = 'Settings'; array_push( $links, $settings_link ); return $links; } }