'text', 'text' => $transcription, 'type' => aiopod_get_transcript_type_from_text( $transcription ) ) ); } } return apply_filters( 'aiopod_get_transcripts', $transcripts, $episode_id ); } /** * Get the transcripts that are actually published and displayed. * * A row is used only when it has content, and only the first row per language counts — a blank * language stands for the podcast's own language. Later duplicates are ignored. * * @since 1.0.5 * @param int $episode_id Episode ID. * @return array Transcript rows, in editor order. */ function aiopod_get_usable_transcripts( $episode_id ) { $transcripts = aiopod_get_transcripts( $episode_id ); $usable = array(); $seen = array(); if ( empty( $transcripts ) ) { return $usable; } $podcast_language = ''; $podcast_id = (int) wp_get_post_parent_id( $episode_id ); if ( $podcast_id > 0 ) { $podcast_language = aiopod_get_podcast_language( $podcast_id ); } foreach ( $transcripts as $transcript ) { if ( ! aiopod_transcript_has_content( $transcript ) ) continue; $language = aiopod_normalize_language_code( ! empty( $transcript['language'] ) ? $transcript['language'] : $podcast_language ); if ( isset( $seen[ $language ] ) ) continue; $seen[ $language ] = true; $usable[] = $transcript; } return $usable; } /** * Give a transcript row every expected key, with consistent types. * * Keys: `source` ('file' or 'text'), `url`, `text`, `type` (MIME type) and `language` (code, or * '' for the podcast's language). * * @since 1.0.5 * @param array $row Transcript row as stored. * @return array Normalised transcript row. */ function aiopod_normalize_transcript( $row ) { $transcript = array( 'source' => ( isset( $row['source'] ) && 'file' === $row['source'] ) ? 'file' : 'text', 'url' => isset( $row['url'] ) ? (string) $row['url'] : '', 'text' => isset( $row['text'] ) ? (string) $row['text'] : '', 'type' => isset( $row['type'] ) ? strtolower( (string) $row['type'] ) : '', 'language' => isset( $row['language'] ) ? strtolower( (string) $row['language'] ) : '' ); return $transcript; } /** * Whether a transcript row has anything to publish. * * @since 1.0.5 * @param array $transcript Normalised transcript row. * @return bool True when a file row has a URL or a text row has text. */ function aiopod_transcript_has_content( $transcript ) { if ( 'file' === $transcript['source'] ) { return '' !== trim( $transcript['url'] ); } return '' !== trim( $transcript['text'] ); } /** * Get the transcript formats the plugin reads and publishes, with their MIME types. * * @since 1.0.5 * @return array Format => MIME type. */ function aiopod_get_transcript_formats() { return array( 'vtt' => 'text/vtt', 'srt' => 'application/x-subrip', 'json' => 'application/json', 'html' => 'text/html', 'txt' => 'text/plain' ); } /** * Get the format a transcript MIME type stands for. * * Imported types are stored as the source feed gave them, so this also recognises the * `application/srt` that PowerPress feeds use, and a type carrying parameters such as * `text/vtt; charset=utf-8`. * * @since 1.0.5 * @param string $type MIME type. * @return string Format key from aiopod_get_transcript_formats(), or '' if unrecognised. */ function aiopod_get_transcript_format( $type ) { $type = strtolower( trim( (string) $type ) ); if ( false !== strpos( $type, ';' ) ) { $type = trim( substr( $type, 0, strpos( $type, ';' ) ) ); } if ( 'application/srt' === $type ) { return 'srt'; } $format = array_search( $type, aiopod_get_transcript_formats(), true ); return false !== $format ? $format : ''; } /** * Detect a transcript file's MIME type from the extension in its URL. * * @since 1.0.5 * @param string $url Transcript file URL. * @return string MIME type, or '' when the extension is missing or not a transcript format. */ function aiopod_get_transcript_type_from_url( $url ) { $path = parse_url( (string) $url, PHP_URL_PATH ); if ( empty( $path ) ) { return ''; } $ext = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ); if ( 'htm' === $ext ) { $ext = 'html'; } $formats = aiopod_get_transcript_formats(); return isset( $formats[ $ext ] ) ? $formats[ $ext ] : ''; } /** * Detect pasted transcript text's MIME type from its content. * * Anything not recognised as VTT, SRT or Podcasting 2.0 JSON is plain text. Pasted HTML is * deliberately plain text too: it is shown escaped, never rendered. * * @since 1.0.5 * @param string $text Transcript text. * @return string MIME type. */ function aiopod_get_transcript_type_from_text( $text ) { $formats = aiopod_get_transcript_formats(); // Ignore a UTF-8 byte order mark and leading blank lines $text = ltrim( preg_replace( '/^\xEF\xBB\xBF/', '', (string) $text ) ); if ( preg_match( '/^WEBVTT(?:[ \t]|\r?\n|$)/', $text ) ) { return $formats['vtt']; } // A numeric cue identifier followed by a timing line, e.g. "1" then "00:00:01,000 --> 00:00:04,000" if ( preg_match( '/^\d+[ \t]*\r?\n[ \t]*\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}[ \t]*-->[ \t]*\d{1,2}:\d{2}:\d{2}[,.]\d{1,3}/', $text ) ) { return $formats['srt']; } if ( 0 === strpos( $text, '{' ) ) { $data = json_decode( $text, true ); if ( is_array( $data ) && isset( $data['segments'] ) && is_array( $data['segments'] ) ) { return $formats['json']; } } return $formats['txt']; } /** * Parse a timed transcript into cues. * * Each cue is an array of `start` and `end` (seconds, float), `speaker` and `text` (plain text, * not escaped). Untimed formats have no cues, and anything that cannot be read gives an empty * array rather than an error. * * @since 1.0.5 * @param string $content Transcript content. * @param string $type MIME type of the content. * @return array Cues, in order. */ function aiopod_parse_transcript( $content, $type ) { $content = (string) $content; // Normalise line endings and drop a UTF-8 byte order mark $content = preg_replace( '/^\xEF\xBB\xBF/', '', $content ); $content = str_replace( array( "\r\n", "\r" ), "\n", $content ); switch ( aiopod_get_transcript_format( $type ) ) { case 'vtt': $cues = aiopod_parse_vtt_transcript( $content ); break; case 'srt': $cues = aiopod_parse_srt_transcript( $content ); break; case 'json': $cues = aiopod_parse_json_transcript( $content ); break; default: $cues = array(); } // In time order, which the episode page's highlighting relies on; equal start times keep their file order if ( count( $cues ) > 1 ) { $starts = array_column( $cues, 'start' ); $order = array_keys( $cues ); array_multisort( $starts, SORT_ASC, SORT_NUMERIC, $order, SORT_ASC, SORT_NUMERIC, $cues ); } return $cues; } /** * Parse WebVTT content into cues. * * Speakers come from `` voice tags, or failing that from a "Name:" prefix. A file that * uses voice tags names the speaker of every cue, so a cue without one has no speaker; a "Name:" * prefix appears only when the speaker changes, so it carries over. Header, NOTE, STYLE and REGION * blocks and cue settings are ignored. * * @since 1.0.5 * @param string $content WebVTT content with "\n" line endings. * @return array Cues. */ function aiopod_parse_vtt_transcript( $content ) { if ( ! preg_match( '/^\s*WEBVTT/', $content ) ) { return array(); } $voice_tag = '/]*)?\s+([^>]+)>/'; $has_voice_tags = (bool) preg_match( $voice_tag, $content ); $cues = array(); $speaker = ''; $blocks = preg_split( '/\n[ \t]*\n/', trim( $content ) ); // The first block is the header array_shift( $blocks ); foreach ( $blocks as $block ) { $lines = explode( "\n", trim( $block ) ); if ( preg_match( '/^(NOTE|STYLE|REGION)\b/', $lines[0] ) ) continue; // An optional cue identifier comes before the timing line if ( false === strpos( $lines[0], '-->' ) ) { array_shift( $lines ); } if ( empty( $lines ) ) continue; $timing = aiopod_parse_transcript_timing( array_shift( $lines ) ); if ( false === $timing ) continue; $payload = implode( "\n", $lines ); if ( preg_match_all( $voice_tag, $payload, $matches ) ) { $voices = array_unique( array_map( 'aiopod_clean_transcript_text', $matches[1] ) ); if ( 1 === count( $voices ) ) { $speaker = reset( $voices ); $text = aiopod_clean_transcript_text( $payload ); } else { // Several speakers in one cue cannot be split without inventing timings, so each keeps their name in the text $speaker = ''; $text = aiopod_clean_transcript_text( preg_replace( $voice_tag, ' $1: ', $payload ) ); } } else { $parts = aiopod_split_transcript_speaker( aiopod_clean_transcript_text( $payload ) ); $text = $parts['text']; if ( '' !== $parts['speaker'] ) { $speaker = $parts['speaker']; } elseif ( $has_voice_tags ) { $speaker = ''; } } if ( '' === $text ) continue; $cues[] = array( 'start' => $timing['start'], 'end' => $timing['end'], 'speaker' => $speaker, 'text' => $text ); } return $cues; } /** * Parse SRT content into cues. * * Speakers come from a "Name:" prefix, which by the Podcasting 2.0 guidance appears only when the * speaker changes — so a speaker carries over to the cues after it. * * @since 1.0.5 * @param string $content SRT content with "\n" line endings. * @return array Cues. */ function aiopod_parse_srt_transcript( $content ) { $cues = array(); $speaker = ''; $blocks = preg_split( '/\n[ \t]*\n/', trim( $content ) ); foreach ( $blocks as $block ) { $lines = explode( "\n", trim( $block ) ); // The numeric index is expected, but tolerated when missing if ( false === strpos( $lines[0], '-->' ) ) { array_shift( $lines ); } if ( empty( $lines ) ) continue; $timing = aiopod_parse_transcript_timing( array_shift( $lines ) ); if ( false === $timing ) continue; $parts = aiopod_split_transcript_speaker( aiopod_clean_transcript_text( implode( "\n", $lines ) ) ); $speaker = '' !== $parts['speaker'] ? $parts['speaker'] : $speaker; if ( '' === $parts['text'] ) continue; $cues[] = array( 'start' => $timing['start'], 'end' => $timing['end'], 'speaker' => $speaker, 'text' => $parts['text'] ); } return $cues; } /** * Parse Podcasting 2.0 JSON content into cues. * * Segments may be whole phrases or single words. Word-level segments are joined into * caption-sized cues — same speaker, up to 65 characters, ending at a sentence break — so that * captions and the episode page are not one word per line. Phrase-level segments are kept as they * are. * * @since 1.0.5 * @param string $content JSON content. * @return array Cues. */ function aiopod_parse_json_transcript( $content ) { $data = json_decode( $content, true ); if ( ! is_array( $data ) || empty( $data['segments'] ) || ! is_array( $data['segments'] ) ) { return array(); } $cues = array(); $current = null; foreach ( $data['segments'] as $segment ) { if ( ! is_array( $segment ) || ! isset( $segment['startTime'] ) || ! is_numeric( $segment['startTime'] ) ) continue; $body = isset( $segment['body'] ) ? (string) $segment['body'] : ''; // Spacing tokens between words carry no text of their own if ( '' === trim( $body ) ) continue; $start = max( 0, (float) $segment['startTime'] ); $end = ( isset( $segment['endTime'] ) && is_numeric( $segment['endTime'] ) ) ? max( $start, (float) $segment['endTime'] ) : $start; $speaker = isset( $segment['speaker'] ) ? aiopod_clean_transcript_text( $segment['speaker'] ) : ''; $text = aiopod_clean_transcript_text( $body ); $is_word = false === strpos( $text, ' ' ); $can_join = $is_word && null !== $current && $current['is_word'] && $speaker === $current['speaker'] && strlen( $current['text'] . ' ' . $text ) <= 65 && ! preg_match( '/[.!?…]$/u', $current['text'] ); if ( $can_join ) { $current['text'] .= ' ' . $text; $current['end'] = max( $current['end'], $end ); continue; } if ( null !== $current ) { unset( $current['is_word'] ); $cues[] = $current; } $current = array( 'start' => $start, 'end' => $end, 'speaker' => $speaker, 'text' => $text, 'is_word' => $is_word ); } if ( null !== $current ) { unset( $current['is_word'] ); $cues[] = $current; } return $cues; } /** * Parse a cue timing line, e.g. "00:00:01.000 --> 00:00:04.000 align:start". * * @since 1.0.5 * @param string $line Timing line. * @return array|false Array of `start` and `end` in seconds, or false if it is not a timing line. */ function aiopod_parse_transcript_timing( $line ) { $parts = explode( '-->', $line, 2 ); if ( 2 !== count( $parts ) ) { return false; } $start = aiopod_parse_transcript_time( trim( $parts[0] ) ); // Cue settings follow the end time $end_parts = preg_split( '/\s+/', trim( $parts[1] ) ); $end = aiopod_parse_transcript_time( $end_parts[0] ); if ( false === $start || false === $end ) { return false; } return array( 'start' => $start, 'end' => max( $start, $end ) ); } /** * Convert a cue timestamp to seconds. * * Accepts "hh:mm:ss.ttt" and "mm:ss.ttt" (WebVTT) and "hh:mm:ss,ttt" (SRT). * * @since 1.0.5 * @param string $time Timestamp. * @return float|false Seconds, or false if it is not a timestamp. */ function aiopod_parse_transcript_time( $time ) { if ( ! preg_match( '/^(?:(\d+):)?(\d{1,2}):(\d{2})(?:[.,](\d{1,3}))?$/', trim( $time ), $matches ) ) { return false; } $hours = '' !== $matches[1] ? (int) $matches[1] : 0; $minutes = (int) $matches[2]; $seconds = (int) $matches[3]; $millis = isset( $matches[4] ) ? (int) str_pad( $matches[4], 3, '0' ) : 0; return (float) ( $hours * 3600 + $minutes * 60 + $seconds + $millis / 1000 ); } /** * Reduce cue markup to plain text. * * Removes WebVTT and HTML tags (voice, class, italic, inline timestamps), decodes entities and * collapses whitespace. The result is plain text, still to be escaped wherever it is output. * * @since 1.0.5 * @param string $text Cue payload. * @return string Plain text. */ function aiopod_clean_transcript_text( $text ) { $text = preg_replace( '/<[^>]*>/', '', (string) $text ); $text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); // Directional marks and non-breaking spaces become ordinary spacing $text = str_replace( array( "\xE2\x80\x8E", "\xE2\x80\x8F" ), '', $text ); $text = preg_replace( '/[\s\x{00A0}]+/u', ' ', $text ); return trim( $text ); } /** * Split a "Name: text" speaker prefix from cue text. * * Deliberately narrow, so ordinary text that happens to contain a colon is left alone: one to four * words, each starting with a capital letter or digit, at most 40 characters, then a colon and a * space. * * @since 1.0.5 * @param string $text Plain cue text. * @return array Array of `speaker` ('' when there is none) and `text`. */ function aiopod_split_transcript_speaker( $text ) { if ( preg_match( '/^([\p{Lu}\d][\p{L}\p{M}\d.\'’-]*(?: [\p{Lu}\d][\p{L}\p{M}\d.\'’-]*){0,3}):\s+(.+)$/u', $text, $matches ) && strlen( $matches[1] ) <= 40 ) { return array( 'speaker' => $matches[1], 'text' => trim( $matches[2] ) ); } return array( 'speaker' => '', 'text' => $text ); } /** * Get the formats a transcript of the given type can be published in. * * Timed sources (VTT, SRT, JSON) give every timed format plus HTML. Untimed sources give HTML and * plain text only: timings are never invented for text that has none. * * @since 1.0.5 * @param string $type MIME type of the source. * @return array Format keys from aiopod_get_transcript_formats(). */ function aiopod_get_transcript_output_formats( $type ) { $format = aiopod_get_transcript_format( $type ); if ( in_array( $format, array( 'vtt', 'srt', 'json' ), true ) ) { return array( 'vtt', 'srt', 'json', 'html' ); } if ( in_array( $format, array( 'html', 'txt' ), true ) ) { return array( 'html', 'txt' ); } return array(); } /** * Build WebVTT from cues. * * Every cue names its speaker in a `` tag. Lines are wrapped at 65 characters, the length the * Podcasting 2.0 guidance recommends for captions. * * @since 1.0.5 * @param array $cues Cues from aiopod_parse_transcript(). * @return string WebVTT content. */ function aiopod_build_vtt_transcript( $cues ) { $output = "WEBVTT\n"; foreach ( $cues as $cue ) { // Escaped as the WebVTT specification allows, so neither text nor speaker can become markup $escape = array( '&' => '&', '<' => '<', '>' => '>' ); $text = aiopod_wrap_transcript_text( strtr( $cue['text'], $escape ), 65 ); if ( '' !== $cue['speaker'] ) { $text = '' . $text; } $output .= "\n" . aiopod_format_transcript_time( $cue['start'], 'vtt' ) . ' --> ' . aiopod_format_transcript_time( $cue['end'], 'vtt' ) . "\n" . $text . "\n"; } return $output; } /** * Build SRT from cues. * * Follows the Podcasting 2.0 guidance where it can: lines of at most 32 characters, and the * speaker's name as a prefix when the speaker changes. Each cue stays one card, so a long cue runs * past the guidance's two lines — splitting it would mean inventing timings the source never had. * * @since 1.0.5 * @param array $cues Cues from aiopod_parse_transcript(). * @return string SRT content. */ function aiopod_build_srt_transcript( $cues ) { $output = ''; $index = 0; $speaker = ''; foreach ( $cues as $cue ) { // SRT has no escaping, so anything tag-like is removed rather than passed on as markup $text = preg_replace( '/<[^>]*>/', '', $cue['text'] ); $text = trim( str_replace( '-->', '->', $text ) ); if ( '' === $text ) continue; if ( '' !== $cue['speaker'] && $cue['speaker'] !== $speaker ) { $text = str_replace( array( '<', '>' ), '', $cue['speaker'] ) . ': ' . $text; } $speaker = $cue['speaker']; $output .= ( ++$index ) . "\n" . aiopod_format_transcript_time( $cue['start'], 'srt' ) . ' --> ' . aiopod_format_transcript_time( $cue['end'], 'srt' ) . "\n" . aiopod_wrap_transcript_text( $text, 32 ) . "\n\n"; } return $output; } /** * Build Podcasting 2.0 JSON from cues. * * @since 1.0.5 * @param array $cues Cues from aiopod_parse_transcript(). * @return string JSON content. */ function aiopod_build_json_transcript( $cues ) { $segments = array(); foreach ( $cues as $cue ) { $segment = array(); if ( '' !== $cue['speaker'] ) { $segment['speaker'] = $cue['speaker']; } $segment['startTime'] = round( $cue['start'], 3 ); $segment['endTime'] = round( $cue['end'], 3 ); $segment['body'] = $cue['text']; $segments[] = $segment; } $data = array( 'version' => '1.0.0', 'segments' => $segments ); return (string) wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG | JSON_HEX_AMP ); } /** * Build a Podcasting 2.0 HTML transcript from cues. * * One passage per run of cues by the same speaker: `` for the speaker, `