PluginProbe
BeyondWords – AI audio for publishers / 4.2.2
BeyondWords – AI audio for publishers v4.2.2
7.2.0 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 All 44 releases
speechkit / src / Component / Post / PostContentUtils.php

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

586 lines 19.0 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 <[email protected]>
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 // https://beyondwords.postman.co/workspace/BeyondWords-Developers~169d849b-f6e1-4a78-8b66-5c87969588fc/request/23751538-99727151-c025-43b3-bd12-66951a042e2c
312 $body = [
313 'type' => 'auto_segment',
314 'title' => get_the_title($postId),
315 'summary' => PostContentUtils::getSummary($postId),
316 'body' => PostContentUtils::getBody($postId),
317 'source_url' => get_the_permalink($postId),
318 'source_id' => strval($postId),
319 'author' => PostContentUtils::getAuthorName($postId),
320 'image_url' => strval(get_the_post_thumbnail_url($postId, [240, 240])),
321 'metadata' => PostContentUtils::getMetadata($postId),
322 'published' => true,
323 'publish_date' => get_post_time(PostContentUtils::DATE_FORMAT, true, $postId),
324 ];
325
326 $status = get_post_status($postId);
327
328 /*
329 * If the post status is "pending" then we send { published: false } to
330 * the BeyondWords API, to prevent the generated audio from being
331 * published in playlists.
332 *
333 * We also omit { publish_date } because get_post_time() returns `false`
334 * for posts which are "Pending Review".
335 */
336 if ($status === 'pending') {
337 $body['published'] = false;
338 unset($body['publish_date']);
339 }
340
341 $bodyVoiceId = intval(get_post_meta($postId, 'beyondwords_body_voice_id', true));
342
343 if ($bodyVoiceId > 0) {
344 $body['body_voice_id'] = $bodyVoiceId;
345 }
346
347 $titleVoiceId = intval(get_post_meta($postId, 'beyondwords_title_voice_id', true));
348
349 if ($titleVoiceId > 0) {
350 $body['title_voice_id'] = $titleVoiceId;
351 }
352
353 $summaryVoiceId = intval(get_post_meta($postId, 'beyondwords_summary_voice_id', true));
354
355 if ($summaryVoiceId > 0) {
356 $body['summary_voice_id'] = $summaryVoiceId;
357 }
358
359 /**
360 * Filters the body params we send to the BeyondWords API when
361 * processing audio.
362 *
363 * @since 4.0.0
364 *
365 * @param array $body The params we send to the BeyondWords API.
366 * @param array $postId WordPress post ID.
367 */
368 $body = apply_filters('beyondwords_body_params', $body, $postId);
369
370 return wp_json_encode($body);
371 }
372
373 /**
374 * Get the post metadata to send with BeyondWords API requests.
375 *
376 * The metadata key is defined by the BeyondWords API as "A custom object
377 * for storing meta information".
378 *
379 * The metadata values are used to create filters for playlists in the
380 * BeyondWords dashboard.
381 *
382 * We currently only include taxonomies by default, and the output of this
383 * method can be filtered using the `beyondwords_post_metadata` filter.
384 *
385 * @since 3.3.0
386 * @since 3.5.0 Moved from Core\Utils to Component\Post\PostUtils
387 *
388 * @param int $postId Post ID.
389 *
390 * @return array
391 */
392 public static function getMetadata($postId)
393 {
394 $metadata = new \stdClass();
395
396 $taxonomy = PostContentUtils::getAllTaxonomiesAndTerms($postId);
397
398 if (count((array)$taxonomy)) {
399 $metadata->taxonomy = $taxonomy;
400 }
401
402 /**
403 * Filters the post metadata sent to the BeyondWords API.
404 *
405 * @since 3.3.0
406 *
407 * @param object $metadata Post metadata. Defaults to the taxonomies and terms assigned to the post.
408 * @param int $postId Post ID.
409 */
410 $metadata = apply_filters('beyondwords_post_metadata', $metadata, $postId);
411
412 return $metadata;
413 }
414
415 /**
416 * Get all taxonomies, and their selected terms, for a post.
417 *
418 * Returns an associative array of taxonomy names and terms.
419 *
420 * For example:
421 *
422 * array(
423 * "categories" => array("Category 1"),
424 * "post_tag" => array("Tag 1", "Tag 2", "Tag 3"),
425 * )
426 *
427 * @since 3.3.0
428 * @since 3.5.0 Moved from Core\Utils to Component\Post\PostUtils
429 *
430 * @param int $postId Post ID.
431 *
432 * @return array
433 */
434 public static function getAllTaxonomiesAndTerms($postId)
435 {
436 $postType = get_post_type($postId);
437
438 $postTypeTaxonomies = get_object_taxonomies($postType);
439
440 $taxonomies = new \stdClass();
441
442 foreach ($postTypeTaxonomies as $postTypeTaxonomy) {
443 $terms = get_the_terms($postId, $postTypeTaxonomy);
444
445 if (! empty($terms) && ! is_wp_error($terms)) {
446 $taxonomies->{(string)$postTypeTaxonomy} = wp_list_pluck($terms, 'name');
447 }
448 }
449
450 return $taxonomies;
451 }
452
453 /**
454 * Get author name for a post.
455 *
456 * @since 3.10.4
457 *
458 * @param int $postId Post ID.
459 *
460 * @return string
461 */
462 public static function getAuthorName($postId)
463 {
464 $authorId = get_post_field('post_author', $postId);
465
466 return get_the_author_meta('display_name', $authorId);
467 }
468
469 /**
470 * Add data-beyondwords-marker attribute to the root elements in a HTML
471 * string (typically the rendered HTML of a single block).
472 *
473 * Checks to see whether we can use WP_HTML_Tag_Processor, or whether we
474 * fall back to using DOMDocument to add the marker.
475 *
476 * @since 4.2.2
477 *
478 * @param string $html HTML.
479 * @param string $marker Marker UUID.
480 *
481 * @return string HTML.
482 */
483 public static function addMarkerAttribute($html, $marker)
484 {
485 if (! $marker) {
486 return $html;
487 }
488
489 // Prefer WP_HTML_Tag_Processor, introduced in WordPress 6.2
490 if (class_exists('WP_HTML_Tag_Processor')) {
491 return PostContentUtils::addMarkerAttributeWithHTMLTagProcessor($html, $marker);
492 } else {
493 return PostContentUtils::addMarkerAttributeWithDOMDocument($html, $marker);
494 }
495 }
496
497 /**
498 * Add data-beyondwords-marker attribute to the root elements in a HTML
499 * string using WP_HTML_Tag_Processor.
500 *
501 * @since 4.0.0
502 * @since 4.2.2 Moved from src/Component/Post/BlockAttributes/BlockAttributes.php
503 * to src/Component/Post/PostContentUtils.php
504 *
505 * @param string $html HTML.
506 * @param string $marker Marker UUID.
507 *
508 * @return string HTML.
509 */
510 public static function addMarkerAttributeWithHTMLTagProcessor($html, $marker)
511 {
512 // https://github.com/WordPress/gutenberg/pull/42485
513 $tags = new \WP_HTML_Tag_Processor($html);
514
515 if ($tags->next_tag()) {
516 $tags->set_attribute('data-beyondwords-marker', $marker);
517 }
518
519 return strval($tags);
520 }
521
522 /**
523 * Add data-beyondwords-marker attribute to the root elements in a HTML
524 * string using DOMDocument.
525 *
526 * This is a fallback, since WP_HTML_Tag_Processor was only shipped with
527 * WordPress 6.2 on 19 April 2023.
528 *
529 * https://make.wordpress.org/core/2022/10/13/whats-new-in-gutenberg-14-3-12-october/
530 *
531 * Note: It is not ideal to do all the $bodyElement/$fullHtml processing
532 * in this method, but without it DOMDocument does not work as expected if
533 * there is more than 1 root element. The approach here has been taken from
534 * some historic Gutenberg code before they implemented WP_HTML_Tag_Processor:
535 *
536 * https://github.com/WordPress/gutenberg/blob/6671cef1179412a2bbd4969cbbc82705c7f69bac/lib/block-supports/index.php
537 *
538 * @since 4.0.0
539 * @since 4.2.2 Moved from src/Component/Post/BlockAttributes/BlockAttributes.php
540 * to src/Component/Post/PostContentUtils.php
541 *
542 * @param string $html HTML.
543 * @param string $marker Marker UUID.
544 *
545 * @return string HTML.
546 */
547 public static function addMarkerAttributeWithDOMDocument($html, $marker)
548 {
549 $dom = new \DOMDocument('1.0', 'utf-8');
550
551 $wrappedHtml =
552 '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body>'
553 . $html
554 . '</body></html>';
555
556 $success = $dom->loadHTML($wrappedHtml, LIBXML_HTML_NODEFDTD | LIBXML_COMPACT);
557
558 if (! $success) {
559 return $html;
560 }
561
562 // Structure is like `<html><head/><body/></html>`, so body is the `lastChild` of our document.
563 $bodyElement = $dom->documentElement->lastChild;
564
565 $xpath = new \DOMXPath($dom);
566 $blockRoot = $xpath->query('./*', $bodyElement)[0];
567
568 if (empty($blockRoot)) {
569 return $html;
570 }
571
572 $blockRoot->setAttribute('data-beyondwords-marker', $marker);
573
574 // Avoid using `$dom->saveHtml( $node )` because the node results may not produce consistent
575 // whitespace. Saving the root HTML `$dom->saveHtml()` prevents this behavior.
576 $fullHtml = $dom->saveHtml();
577
578 // Find the <body> open/close tags. The open tag needs to be adjusted so we get inside the tag
579 // and not the tag itself.
580 $start = strpos($fullHtml, '<body>', 0) + strlen('<body>');
581 $end = strpos($fullHtml, '</body>', $start);
582
583 return trim(substr($fullHtml, $start, $end - $start));
584 }
585 }
586