PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 27.5
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v27.5
28.5 28.4 28.3 28.2 28.1 28.0 27.9 27.8 27.7 27.6 27.5 trunk 18.0 18.1 18.2 18.3 18.4 18.4.1 18.5 18.5.1 18.6 18.7 18.8 18.9 19.0 All 129 releases
wordpress-seo / src / ai / generator / application / suggestions-provider.php

suggestions-provider.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 27.5, at src/ai/generator/application/suggestions-provider.php

179 lines 6.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 // phpcs:disable Yoast.NamingConventions.NamespaceName.TooLong -- Needed in the folder structure.
4
5 namespace Yoast\WP\SEO\AI\Generator\Application;
6
7 use RuntimeException;
8 use WP_User;
9 use Yoast\WP\SEO\AI\Authorization\Application\Token_Manager;
10 use Yoast\WP\SEO\AI\Consent\Application\Consent_Handler;
11 use Yoast\WP\SEO\AI\Generator\Domain\Suggestion;
12 use Yoast\WP\SEO\AI\Generator\Domain\Suggestions_Bucket;
13 use Yoast\WP\SEO\AI\HTTP_Request\Application\Request_Handler;
14 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Bad_Request_Exception;
15 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Forbidden_Exception;
16 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Internal_Server_Error_Exception;
17 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Not_Found_Exception;
18 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Payment_Required_Exception;
19 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Request_Timeout_Exception;
20 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Service_Unavailable_Exception;
21 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Too_Many_Requests_Exception;
22 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Exceptions\Unauthorized_Exception;
23 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Request;
24 use Yoast\WP\SEO\AI\HTTP_Request\Domain\Response;
25 use Yoast\WP\SEO\Helpers\User_Helper;
26
27 /**
28 * The class that handles the suggestions from the AI API.
29 */
30 class Suggestions_Provider {
31
32 /**
33 * The consent handler instance.
34 *
35 * @var Consent_Handler
36 */
37 private $consent_handler;
38
39 /**
40 * The request handler instance.
41 *
42 * @var Request_Handler
43 */
44 private $request_handler;
45
46 /**
47 * The token manager instance.
48 *
49 * @var Token_Manager
50 */
51 private $token_manager;
52
53 /**
54 * The user helper instance.
55 *
56 * @var User_Helper
57 */
58 private $user_helper;
59
60 /**
61 * Class constructor.
62 *
63 * @param Consent_Handler $consent_handler The consent handler instance.
64 * @param Request_Handler $request_handler The request handler instance.
65 * @param Token_Manager $token_manager The token manager instance.
66 * @param User_Helper $user_helper The user helper instance.
67 */
68 public function __construct(
69 Consent_Handler $consent_handler,
70 Request_Handler $request_handler,
71 Token_Manager $token_manager,
72 User_Helper $user_helper
73 ) {
74 $this->consent_handler = $consent_handler;
75 $this->request_handler = $request_handler;
76 $this->token_manager = $token_manager;
77 $this->user_helper = $user_helper;
78 }
79
80 // phpcs:disable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber -- PHPCS doesn't take into account exceptions thrown in called methods.
81
82 /**
83 * Method used to generate suggestions through AI.
84 *
85 * @param WP_User $user The WP user.
86 * @param string $suggestion_type The type of the requested suggestion.
87 * @param string $prompt_content The excerpt taken from the post.
88 * @param string $focus_keyphrase The focus keyphrase associated to the post.
89 * @param string $language The language of the post.
90 * @param string $platform The platform the post is intended for.
91 * @param string $editor The current editor.
92 * @param bool $retry_on_unauthorized Whether to retry when unauthorized (mechanism to retry once).
93 *
94 * @throws Bad_Request_Exception Bad_Request_Exception.
95 * @throws Forbidden_Exception Forbidden_Exception.
96 * @throws Internal_Server_Error_Exception Internal_Server_Error_Exception.
97 * @throws Not_Found_Exception Not_Found_Exception.
98 * @throws Payment_Required_Exception Payment_Required_Exception.
99 * @throws Request_Timeout_Exception Request_Timeout_Exception.
100 * @throws Service_Unavailable_Exception Service_Unavailable_Exception.
101 * @throws Too_Many_Requests_Exception Too_Many_Requests_Exception.
102 * @throws Unauthorized_Exception Unauthorized_Exception.
103 * @throws RuntimeException Unable to retrieve the access token.
104 * @return string[] The suggestions.
105 */
106 public function get_suggestions(
107 WP_User $user,
108 string $suggestion_type,
109 string $prompt_content,
110 string $focus_keyphrase,
111 string $language,
112 string $platform,
113 string $editor,
114 bool $retry_on_unauthorized = true
115 ): array {
116 $token = $this->token_manager->get_or_request_access_token( $user );
117
118 $request_body = [
119 'service' => 'openai',
120 'user_id' => (string) $user->ID,
121 'subject' => [
122 'content' => $prompt_content,
123 'focus_keyphrase' => $focus_keyphrase,
124 'language' => $language,
125 'platform' => $platform,
126 ],
127 ];
128 $request_headers = [
129 'Authorization' => "Bearer $token",
130 'X-Yst-Cohort' => $editor,
131 ];
132
133 try {
134 $response = $this->request_handler->handle( new Request( "/openai/suggestions/$suggestion_type", $request_body, $request_headers ) );
135 } catch ( Unauthorized_Exception $exception ) {
136 // Delete the stored JWT tokens, as they appear to be no longer valid.
137 $this->user_helper->delete_meta( $user->ID, '_yoast_wpseo_ai_generator_access_jwt' );
138 $this->user_helper->delete_meta( $user->ID, '_yoast_wpseo_ai_generator_refresh_jwt' );
139
140 if ( ! $retry_on_unauthorized ) {
141 throw $exception;
142 }
143
144 // Try again once more by fetching a new set of tokens and trying the suggestions endpoint again.
145 return $this->get_suggestions( $user, $suggestion_type, $prompt_content, $focus_keyphrase, $language, $platform, $editor, false );
146 } catch ( Forbidden_Exception $exception ) {
147 // Follow the API in the consent being revoked (Use case: user sent an e-mail to revoke?).
148 // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- false positive.
149 $this->consent_handler->revoke_consent( $user->ID );
150 throw new Forbidden_Exception( 'CONSENT_REVOKED', $exception->getCode() );
151 // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped
152 }
153
154 return $this->build_suggestions_array( $response )->to_array();
155 }
156
157 // phpcs:enable Squiz.Commenting.FunctionCommentThrowTag.WrongNumber
158
159 /**
160 * Generates the list of 5 suggestions to return.
161 *
162 * @param Response $response The response from the API.
163 *
164 * @return Suggestions_Bucket The array of suggestions.
165 */
166 public function build_suggestions_array( Response $response ): Suggestions_Bucket {
167 $suggestions_bucket = new Suggestions_Bucket();
168 $json = \json_decode( $response->get_body() );
169 if ( $json === null || ! isset( $json->choices ) ) {
170 return $suggestions_bucket;
171 }
172 foreach ( $json->choices as $suggestion ) {
173 $suggestions_bucket->add_suggestion( new Suggestion( $suggestion->text ) );
174 }
175
176 return $suggestions_bucket;
177 }
178 }
179