PluginProbe
BeyondWords – AI audio for publishers / 4.2.4
BeyondWords – AI audio for publishers v4.2.4
7.1.0 trunk 4.0.0 4.0.1 4.0.2 4.0.3 4.0.4 4.0.5 4.0.6 4.1.0 4.1.1 4.1.2 4.2.0 4.2.1 4.2.2 4.2.3 4.2.4 4.3.0 4.4.0 4.5.0 4.5.1 4.6.0 4.6.1 4.6.2 4.7.0 All 43 releases
speechkit / src / Component / Post / PostContentUtils.php

PostContentUtils.php in BeyondWords – AI audio for publishers 4.2.4, at src/Component/Post/PostContentUtils.php

585 lines 18.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Beyondwords\Wordpress\Component\Post;
6
7 /**
8 * BeyondWords Post Content Utilities.
9 *
10 * @package Beyondwords
11 * @subpackage Beyondwords/includes
12 * @author Stuart McAlpine <stu@beyondwords.io>
13 * @since 3.5.0
14 */
15 class PostContentUtils
16 {
17 public const DATE_FORMAT = 'Y-m-d\TH:i:s\Z';
18
19 /**
20 * Get the source text for the audio, ready to be sent to the BeyondWords API.
21 *
22 * @deprecated 4.0.0 Renamed to PostContentUtils::getBody()
23 *
24 * @param int|WP_Post $post The WordPress post ID, or post object.
25 *
26 * @since 3.0.0
27 * @since 3.5.0 Moved from Core\Utils to Component\Post\PostUtils
28 * @since 3.8.0 Exclude Gutenberg blocks with attribute { beyondwordsAudio: false }
29 * @since 4.0.0 Renamed from PostContentUtils::getSourceTextForAudio() to PostContentUtils::getBody()
30 *
31 * @return string The body (the processed $post->post_content).
32 */
33 public static function getSourceTextForAudio($post)
34 {
35 _doing_it_wrong(
36 'PostContentUtils::getBody',
37 'BeyondWords PostContentUtils::getSourceTextForAudio() has been renamed to PostContentUtils::getBody()',
38 '4.0.0'
39 );
40
41 return PostContentUtils::getBody($post);
42 }
43
44 /**
45 * Get the body for the audio, ready to be sent to the BeyondWords API.
46 *
47 * The following rules are applied:
48 *
49 * Main body content entered in WordPress
50 * + Optionally filtered using [SpeechKit-Start]/[SpeechKit-Stop] "shortcodes"
51 * + With registered content filters FROM OTHER PLUGINS applied
52 * + Optionally prepended with the Post excerpt
53 * + Optionally filtered using the beyondwords_content filter
54 *
55 * @SuppressWarnings(PHPMD.LongVariable)
56 *
57 * @param int|WP_Post $post The WordPress post ID, or post object.
58 *
59 * @since 3.0.0
60 * @since 3.5.0 Moved from Core\Utils to Component\Post\PostUtils
61 * @since 3.8.0 Exclude Gutenberg blocks with attribute { beyondwordsAudio: false }
62 * @since 4.0.0 Renamed from PostContentUtils::getSourceTextForAudio() to PostContentUtils::getBody()
63 *
64 * @return string The body (the processed $post->post_content).
65 */
66 public static function getBody($post)
67 {
68 global $beyondwords_wordpress_plugin;
69
70 $post = get_post($post);
71
72 if (!($post instanceof \WP_Post)) {
73 throw new \Exception('Post Not Found');
74 }
75
76 $content = PostContentUtils::getContentWithoutExcludedBlocks($post);
77
78 // If SpeechKit-Start/Stop tags are present then use the content within them
79 // @deprecated v3.0.0: publishers should use the beyondwords_content filter instead.
80 $regex = '/\[SpeechKit-Start\](.*?)\[SpeechKit-Stop\]/s';
81
82 if (preg_match_all($regex, $content, $match, PREG_PATTERN_ORDER) > 0) {
83 $content = implode(' ', $match[1]);
84 }
85
86 // Temporarily remove our Player filter, to exclude the player <div>
87 if ($beyondwords_wordpress_plugin && isset($beyondwords_wordpress_plugin->player)) {
88 remove_filter('the_content', array($beyondwords_wordpress_plugin->player, 'autoPrependPlayer'));
89 }
90
91 // Apply other standard WordPress filters to handle shortcodes etc
92 $content = apply_filters('the_content', $content);
93
94 // Add our Player filter back in again
95 if ($beyondwords_wordpress_plugin && isset($beyondwords_wordpress_plugin->player)) {
96 add_filter('the_content', array($beyondwords_wordpress_plugin->player, 'autoPrependPlayer'));
97 }
98
99 // TODO maybe we need to do something like this to deal with Shortcodes a little better?
100 // $content = wp_strip_all_tags(apply_filters('the_content', $content));
101
102 // Trim to remove trailing newlines – common for WordPress content
103 $content = trim($content);
104
105 /**
106 * Filters the content body we send for audio processing.
107 *
108 * @since 4.0.0
109 *
110 * @param string $content The post content.
111 * @param int $postId The post ID.
112 */
113 $content = apply_filters('beyondwords_content', $content, $post->ID);
114
115 return $content;
116 }
117
118 /**
119 * Get the summary for the audio content, ready to be sent to the BeyondWords API.
120 *
121 * @param int|WP_Post $post The WordPress post ID, or post object.
122 *
123 * @since 4.0.0
124 *
125 * @return string The summary.
126 */
127 public static function getSummary($post)
128 {
129 $post = get_post($post);
130
131 if (!($post instanceof \WP_Post)) {
132 throw new \Exception('Post Not Found');
133 }
134
135 $summary = null;
136
137 // Optionally send the excerpt to the REST API, if the plugin setting has been checked
138 $prependExcerpt = get_option('beyondwords_prepend_excerpt');
139
140 if ($prependExcerpt && has_excerpt($post)) {
141 // Escape characters
142 $summary = htmlentities($post->post_excerpt, ENT_QUOTES | ENT_XHTML);
143 // Apply WordPress filters
144 $summary = apply_filters('get_the_excerpt', $summary);
145 // Convert line breaks into paragraphs
146 $summary = trim(wpautop($summary));
147 }
148
149 return $summary;
150 }
151
152 /**
153 * Get the segments for the audio content, ready to be sent to the BeyondWords API.
154 *
155 * THIS METHOD IS CURRENTLY NOT IN USE. Segments cannot currently include HTML
156 * formatting tags such as <strong> and <em> so we do not pass segments, we pass
157 * a HTML string as the body param instead.
158 *
159 * @param int|WP_Post $post The WordPress post ID, or post object.
160 *
161 * @since 4.0.0
162 *
163 * @return array|null The segments.
164 */
165 public static function getSegments($post)
166 {
167 if (! has_blocks($post)) {
168 return null;
169 }
170
171 $titleSegment = (object) [
172 'section' => 'title',
173 'text' => get_the_title($post),
174 ];
175
176 $summarySegment = (object) [
177 'section' => 'summary',
178 'text' => PostContentUtils::getSummary($post),
179 ];
180
181 $blocks = PostContentUtils::getAudioEnabledBlocks($post);
182
183 $bodySegments = array_map(function ($block) {
184 $marker = null;
185
186 if (isset($block['attrs']) && isset($block['attrs']['beyondwordsMarker'])) {
187 $marker = $block['attrs']['beyondwordsMarker'];
188 }
189
190 return (object) [
191 'section' => 'body',
192 'marker' => $marker,
193 'text' => trim(render_block($block)),
194 ];
195 }, $blocks);
196
197 // Merge title, summary and body segments
198 $segments = array_values(array_merge([$titleSegment], [$summarySegment], $bodySegments));
199
200 // TODO Consider removing this when API can handle it
201 // Remove any segments with empty text
202 $segments = array_values(array_filter($segments, function ($segment) {
203 return (! empty($segment->text));
204 }));
205
206 return $segments;
207 }
208
209 /**
210 * Get the post content without blocks which have been filtered.
211 *
212 * We have added buttons into the Gutenberg editor to optionally exclude selected
213 * blocks from the source text for audio.
214 *
215 * This method filters all blocks, removing any which have been excluded.
216 *
217 * @param int|WP_Post $post The WordPress post ID, or post object.
218 *
219 * @since 3.8.0
220 * @since 4.0.0 Replace for loop with array_reduce
221 *
222 * @return string The post body without excluded blocks.
223 */
224 public static function getContentWithoutExcludedBlocks($post)
225 {
226 if (! has_blocks($post)) {
227 return trim($post->post_content);
228 }
229
230 $blocks = parse_blocks($post->post_content);
231 $output = '';
232
233 $blocks = PostContentUtils::getAudioEnabledBlocks($post);
234
235 foreach ($blocks as $block) {
236 $marker = $block['attrs']['beyondwordsMarker'] ?? '';
237
238 $output .= PostContentUtils::addMarkerAttribute(
239 render_block($block),
240 $marker
241 );
242 }
243
244 return $output;
245 }
246
247 /**
248 * Get audio-enabled blocks.
249 *
250 * @param int|WP_Post $post The WordPress post ID, or post object.
251 *
252 * @since 4.0.0
253 *
254 * @return array The blocks.
255 */
256 public static function getAudioEnabledBlocks($post)
257 {
258 $post = get_post($post);
259
260 if (! ($post instanceof \WP_Post)) {
261 return [];
262 }
263
264 if (! has_blocks($post)) {
265 return [];
266 }
267
268 $allBlocks = parse_blocks($post->post_content);
269
270 $blocks = array_filter($allBlocks, function ($block) {
271 $enabled = true;
272
273 if (is_array($block['attrs']) && isset($block['attrs']['beyondwordsAudio'])) {
274 $enabled = (bool) $block['attrs']['beyondwordsAudio'];
275 }
276
277 return $enabled;
278 });
279
280 /**
281 * Filters the audio-enabled blocks for a post.
282 *
283 * @since 4.0.0
284 *
285 * @param array $blocks The audio-enabled post blocks.
286 * @param array $allBlocks All post blocks including those with audio disabled.
287 * @param int $postId The post ID.
288 */
289 $blocks = apply_filters('beyondwords_post_audio_enabled_blocks', $blocks, $allBlocks, $post->ID);
290
291 return $blocks;
292 }
293
294 /**
295 * Get the body param we pass to the API.
296 *
297 * @since 3.0.0
298 * @since 3.3.0 Added metadata to aid custom playlist generation.
299 * @since 3.5.0 Moved from Core\Utils to Component\Post\PostUtils.
300 * @since 3.10.4 Rename `published_at` API param to `publish_date`.
301 * @since 4.0.0 Use new API params.
302 * @since 4.0.3 Ensure `image_url` is always a string.
303 *
304 * @static
305 * @param int $postId WordPress Post ID.
306 *
307 * @return Response
308 **/
309 public static function getBodyJson($postId)
310 {
311 $body = [
312 'type' => 'auto_segment',
313 'title' => get_the_title($postId),
314 'summary' => PostContentUtils::getSummary($postId),
315 'body' => PostContentUtils::getBody($postId),
316 'source_url' => get_the_permalink($postId),
317 'source_id' => strval($postId),
318 'author' => PostContentUtils::getAuthorName($postId),
319 'image_url' => strval(wp_get_original_image_url(get_post_thumbnail_id($postId))),
320 'metadata' => PostContentUtils::getMetadata($postId),
321 'published' => true,
322 'publish_date' => get_post_time(PostContentUtils::DATE_FORMAT, true, $postId),
323 ];
324
325 $status = get_post_status($postId);
326
327 /*
328 * If the post status is "pending" then we send { published: false } to
329 * the BeyondWords API, to prevent the generated audio from being
330 * published in playlists.
331 *
332 * We also omit { publish_date } because get_post_time() returns `false`
333 * for posts which are "Pending Review".
334 */
335 if ($status === 'pending') {
336 $body['published'] = false;
337 unset($body['publish_date']);
338 }
339
340 $bodyVoiceId = intval(get_post_meta($postId, 'beyondwords_body_voice_id', true));
341
342 if ($bodyVoiceId > 0) {
343 $body['body_voice_id'] = $bodyVoiceId;
344 }
345
346 $titleVoiceId = intval(get_post_meta($postId, 'beyondwords_title_voice_id', true));
347
348 if ($titleVoiceId > 0) {
349 $body['title_voice_id'] = $titleVoiceId;
350 }
351
352 $summaryVoiceId = intval(get_post_meta($postId, 'beyondwords_summary_voice_id', true));
353
354 if ($summaryVoiceId > 0) {
355 $body['summary_voice_id'] = $summaryVoiceId;
356 }
357
358 /**
359 * Filters the body params we send to the BeyondWords API when
360 * processing audio.
361 *
362 * @since 4.0.0
363 *
364 * @param array $body The params we send to the BeyondWords API.
365 * @param array $postId WordPress post ID.
366 */
367 $body = apply_filters('beyondwords_body_params', $body, $postId);
368
369 return wp_json_encode($body);
370 }
371
372 /**
373 * Get the post metadata to send with BeyondWords API requests.
374 *
375 * The metadata key is defined by the BeyondWords API as "A custom object
376 * for storing meta information".
377 *
378 * The metadata values are used to create filters for playlists in the
379 * BeyondWords dashboard.
380 *
381 * We currently only include taxonomies by default, and the output of this
382 * method can be filtered using the `beyondwords_post_metadata` filter.
383 *
384 * @since 3.3.0
385 * @since 3.5.0 Moved from Core\Utils to Component\Post\PostUtils
386 *
387 * @param int $postId Post ID.
388 *
389 * @return array
390 */
391 public static function getMetadata($postId)
392 {
393 $metadata = new \stdClass();
394
395 $taxonomy = PostContentUtils::getAllTaxonomiesAndTerms($postId);
396
397 if (count((array)$taxonomy)) {
398 $metadata->taxonomy = $taxonomy;
399 }
400
401 /**
402 * Filters the post metadata sent to the BeyondWords API.
403 *
404 * @since 3.3.0
405 *
406 * @param object $metadata Post metadata. Defaults to the taxonomies and terms assigned to the post.
407 * @param int $postId Post ID.
408 */
409 $metadata = apply_filters('beyondwords_post_metadata', $metadata, $postId);
410
411 return $metadata;
412 }
413
414 /**
415 * Get all taxonomies, and their selected terms, for a post.
416 *
417 * Returns an associative array of taxonomy names and terms.
418 *
419 * For example:
420 *
421 * array(
422 * "categories" => array("Category 1"),
423 * "post_tag" => array("Tag 1", "Tag 2", "Tag 3"),
424 * )
425 *
426 * @since 3.3.0
427 * @since 3.5.0 Moved from Core\Utils to Component\Post\PostUtils
428 *
429 * @param int $postId Post ID.
430 *
431 * @return array
432 */
433 public static function getAllTaxonomiesAndTerms($postId)
434 {
435 $postType = get_post_type($postId);
436
437 $postTypeTaxonomies = get_object_taxonomies($postType);
438
439 $taxonomies = new \stdClass();
440
441 foreach ($postTypeTaxonomies as $postTypeTaxonomy) {
442 $terms = get_the_terms($postId, $postTypeTaxonomy);
443
444 if (! empty($terms) && ! is_wp_error($terms)) {
445 $taxonomies->{(string)$postTypeTaxonomy} = wp_list_pluck($terms, 'name');
446 }
447 }
448
449 return $taxonomies;
450 }
451
452 /**
453 * Get author name for a post.
454 *
455 * @since 3.10.4
456 *
457 * @param int $postId Post ID.
458 *
459 * @return string
460 */
461 public static function getAuthorName($postId)
462 {
463 $authorId = get_post_field('post_author', $postId);
464
465 return get_the_author_meta('display_name', $authorId);
466 }
467
468 /**
469 * Add data-beyondwords-marker attribute to the root elements in a HTML
470 * string (typically the rendered HTML of a single block).
471 *
472 * Checks to see whether we can use WP_HTML_Tag_Processor, or whether we
473 * fall back to using DOMDocument to add the marker.
474 *
475 * @since 4.2.2
476 *
477 * @param string $html HTML.
478 * @param string $marker Marker UUID.
479 *
480 * @return string HTML.
481 */
482 public static function addMarkerAttribute($html, $marker)
483 {
484 if (! $marker) {
485 return $html;
486 }
487
488 // Prefer WP_HTML_Tag_Processor, introduced in WordPress 6.2
489 if (class_exists('WP_HTML_Tag_Processor')) {
490 return PostContentUtils::addMarkerAttributeWithHTMLTagProcessor($html, $marker);
491 } else {
492 return PostContentUtils::addMarkerAttributeWithDOMDocument($html, $marker);
493 }
494 }
495
496 /**
497 * Add data-beyondwords-marker attribute to the root elements in a HTML
498 * string using WP_HTML_Tag_Processor.
499 *
500 * @since 4.0.0
501 * @since 4.2.2 Moved from src/Component/Post/BlockAttributes/BlockAttributes.php
502 * to src/Component/Post/PostContentUtils.php
503 *
504 * @param string $html HTML.
505 * @param string $marker Marker UUID.
506 *
507 * @return string HTML.
508 */
509 public static function addMarkerAttributeWithHTMLTagProcessor($html, $marker)
510 {
511 // https://github.com/WordPress/gutenberg/pull/42485
512 $tags = new \WP_HTML_Tag_Processor($html);
513
514 if ($tags->next_tag()) {
515 $tags->set_attribute('data-beyondwords-marker', $marker);
516 }
517
518 return strval($tags);
519 }
520
521 /**
522 * Add data-beyondwords-marker attribute to the root elements in a HTML
523 * string using DOMDocument.
524 *
525 * This is a fallback, since WP_HTML_Tag_Processor was only shipped with
526 * WordPress 6.2 on 19 April 2023.
527 *
528 * https://make.wordpress.org/core/2022/10/13/whats-new-in-gutenberg-14-3-12-october/
529 *
530 * Note: It is not ideal to do all the $bodyElement/$fullHtml processing
531 * in this method, but without it DOMDocument does not work as expected if
532 * there is more than 1 root element. The approach here has been taken from
533 * some historic Gutenberg code before they implemented WP_HTML_Tag_Processor:
534 *
535 * https://github.com/WordPress/gutenberg/blob/6671cef1179412a2bbd4969cbbc82705c7f69bac/lib/block-supports/index.php
536 *
537 * @since 4.0.0
538 * @since 4.2.2 Moved from src/Component/Post/BlockAttributes/BlockAttributes.php
539 * to src/Component/Post/PostContentUtils.php
540 *
541 * @param string $html HTML.
542 * @param string $marker Marker UUID.
543 *
544 * @return string HTML.
545 */
546 public static function addMarkerAttributeWithDOMDocument($html, $marker)
547 {
548 $dom = new \DOMDocument('1.0', 'utf-8');
549
550 $wrappedHtml =
551 '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>'
552 . $html
553 . '</body></html>';
554
555 $success = $dom->loadHTML($wrappedHtml, LIBXML_HTML_NODEFDTD | LIBXML_COMPACT);
556
557 if (! $success) {
558 return $html;
559 }
560
561 // Structure is like `<html><head/><body/></html>`, so body is the `lastChild` of our document.
562 $bodyElement = $dom->documentElement->lastChild;
563
564 $xpath = new \DOMXPath($dom);
565 $blockRoot = $xpath->query('./*', $bodyElement)[0];
566
567 if (empty($blockRoot)) {
568 return $html;
569 }
570
571 $blockRoot->setAttribute('data-beyondwords-marker', $marker);
572
573 // Avoid using `$dom->saveHtml( $node )` because the node results may not produce consistent
574 // whitespace. Saving the root HTML `$dom->saveHtml()` prevents this behavior.
575 $fullHtml = $dom->saveHtml();
576
577 // Find the <body> open/close tags. The open tag needs to be adjusted so we get inside the tag
578 // and not the tag itself.
579 $start = strpos($fullHtml, '<body>', 0) + strlen('<body>');
580 $end = strpos($fullHtml, '</body>', $start);
581
582 return trim(substr($fullHtml, $start, $end - $start));
583 }
584 }
585