PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 28.5
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v28.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 / bulk-editor / user-interface / bulk-editor-integration.php

bulk-editor-integration.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 28.5, at src/bulk-editor/user-interface/bulk-editor-integration.php

487 lines 16.9 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 namespace Yoast\WP\SEO\Bulk_Editor\User_Interface;
5
6 use WPSEO_Admin_Asset_Manager;
7 use WPSEO_Admin_Editor_Specific_Replace_Vars;
8 use WPSEO_Admin_Recommended_Replace_Vars;
9 use WPSEO_Replace_Vars;
10 use Yoast\WP\SEO\Bulk_Editor\Application\Content_Types\Content_Types_Repository;
11 use Yoast\WP\SEO\Bulk_Editor\Application\Endpoints\Endpoints_Repository;
12 use Yoast\WP\SEO\Bulk_Editor\Domain\Updates\Batch_Limit;
13 use Yoast\WP\SEO\Bulk_Editor\Infrastructure\Nonces\Nonce_Repository;
14 use Yoast\WP\SEO\Conditionals\Admin_Conditional;
15 use Yoast\WP\SEO\General\User_Interface\General_Page_Integration;
16 use Yoast\WP\SEO\Helpers\Current_Page_Helper;
17 use Yoast\WP\SEO\Helpers\Options_Helper;
18 use Yoast\WP\SEO\Helpers\Product_Helper;
19 use Yoast\WP\SEO\Helpers\Short_Link_Helper;
20 use Yoast\WP\SEO\Helpers\User_Helper;
21 use Yoast\WP\SEO\Integrations\Integration_Interface;
22 use Yoast\WP\SEO\MyYoast_Client\User_Interface\Myyoast_Connection_Data_Presenter;
23
24 /**
25 * Adds the bulk editor page to the Yoast admin menu.
26 */
27 class Bulk_Editor_Integration implements Integration_Interface {
28
29 /**
30 * The page name.
31 */
32 public const PAGE = 'wpseo_page_bulk_edit';
33
34 /**
35 * The assets name.
36 */
37 public const ASSETS_NAME = 'bulk-editor-page';
38
39 /**
40 * The URL parameter carrying the content type to preselect.
41 */
42 public const CONTENT_TYPE_PARAM = 'content_type';
43
44 /**
45 * The URL parameter carrying the post IDs to preselect, comma-separated.
46 */
47 public const POST_IDS_PARAM = 'post_ids';
48
49 /**
50 * The URL parameter carrying how many posts were selected on the overview the user came from.
51 */
52 public const SELECTED_COUNT_PARAM = 'selected_count';
53
54 /**
55 * Holds the WPSEO_Admin_Asset_Manager.
56 *
57 * @var WPSEO_Admin_Asset_Manager
58 */
59 private $asset_manager;
60
61 /**
62 * Holds the Current_Page_Helper.
63 *
64 * @var Current_Page_Helper
65 */
66 private $current_page_helper;
67
68 /**
69 * Holds the Product_Helper.
70 *
71 * @var Product_Helper
72 */
73 private $product_helper;
74
75 /**
76 * Holds the Short_Link_Helper.
77 *
78 * @var Short_Link_Helper
79 */
80 private $short_link_helper;
81
82 /**
83 * Holds the Content_Types_Repository.
84 *
85 * @var Content_Types_Repository
86 */
87 private $content_types_repository;
88
89 /**
90 * Holds the Nonce_Repository.
91 *
92 * @var Nonce_Repository
93 */
94 private $nonce_repository;
95
96 /**
97 * Holds the Endpoints_Repository.
98 *
99 * @var Endpoints_Repository
100 */
101 private $endpoints_repository;
102
103 /**
104 * Holds the Options_Helper.
105 *
106 * @var Options_Helper
107 */
108 private $options_helper;
109
110 /**
111 * Holds the User_Helper.
112 *
113 * @var User_Helper
114 */
115 private $user_helper;
116
117 /**
118 * Builds the MyYoast connection payload for script data.
119 *
120 * @var Myyoast_Connection_Data_Presenter
121 */
122 private $myyoast_connection_data_presenter;
123
124 /**
125 * The replace vars handler, used to build the replacement variable list for the editor.
126 *
127 * @var WPSEO_Replace_Vars
128 */
129 private $replace_vars;
130
131 /**
132 * Constructs the instance.
133 *
134 * @param WPSEO_Admin_Asset_Manager $asset_manager The WPSEO_Admin_Asset_Manager.
135 * @param Current_Page_Helper $current_page_helper The Current_Page_Helper.
136 * @param Product_Helper $product_helper The Product_Helper.
137 * @param Short_Link_Helper $short_link_helper The Short_Link_Helper.
138 * @param Content_Types_Repository $content_types_repository The Content_Types_Repository.
139 * @param Nonce_Repository $nonce_repository The Nonce_Repository.
140 * @param Endpoints_Repository $endpoints_repository The Endpoints_Repository.
141 * @param Options_Helper $options_helper The Options_Helper.
142 * @param User_Helper $user_helper The User_Helper.
143 * @param Myyoast_Connection_Data_Presenter $myyoast_connection_data_presenter The MyYoast connection data presenter.
144 * @param WPSEO_Replace_Vars $replace_vars The replace vars handler.
145 */
146 public function __construct(
147 WPSEO_Admin_Asset_Manager $asset_manager,
148 Current_Page_Helper $current_page_helper,
149 Product_Helper $product_helper,
150 Short_Link_Helper $short_link_helper,
151 Content_Types_Repository $content_types_repository,
152 Nonce_Repository $nonce_repository,
153 Endpoints_Repository $endpoints_repository,
154 Options_Helper $options_helper,
155 User_Helper $user_helper,
156 Myyoast_Connection_Data_Presenter $myyoast_connection_data_presenter,
157 WPSEO_Replace_Vars $replace_vars
158 ) {
159 $this->asset_manager = $asset_manager;
160 $this->current_page_helper = $current_page_helper;
161 $this->product_helper = $product_helper;
162 $this->short_link_helper = $short_link_helper;
163 $this->content_types_repository = $content_types_repository;
164 $this->nonce_repository = $nonce_repository;
165 $this->endpoints_repository = $endpoints_repository;
166 $this->options_helper = $options_helper;
167 $this->user_helper = $user_helper;
168 $this->myyoast_connection_data_presenter = $myyoast_connection_data_presenter;
169 $this->replace_vars = $replace_vars;
170 }
171
172 /**
173 * Returns the conditionals based on which this loadable should be active.
174 *
175 * @return array<string> The conditionals.
176 */
177 public static function get_conditionals() {
178 return [ Admin_Conditional::class ];
179 }
180
181 /**
182 * Initializes the integration.
183 *
184 * This is the place to register hooks and filters.
185 *
186 * @return void
187 */
188 public function register_hooks() {
189 \add_filter( 'wpseo_submenu_pages', [ $this, 'add_page' ] );
190
191 // Hide the menu item without losing the page. See remove_menu_item() for why this runs on admin_head.
192 \add_action( 'admin_head', [ $this, 'remove_menu_item' ] );
193
194 // Are we on our page?
195 if ( $this->current_page_helper->get_current_yoast_seo_page() === self::PAGE ) {
196 \add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
197 \add_action( 'in_admin_header', [ $this, 'remove_notices' ], \PHP_INT_MAX );
198 \add_filter( 'removable_query_args', [ $this, 'add_removable_query_args' ] );
199 }
200 }
201
202 /**
203 * Removes the bulk editor's submenu item from the Yoast SEO menu while keeping the page reachable by URL.
204 *
205 * Runs on admin_head rather than admin_menu on purpose: by then WordPress has already resolved the page's
206 * parent and capability (so the page stays accessible and keeps its `seo_page_wpseo_page_bulk_edit` body
207 * class, which its styles depend on), but the menu HTML has not been rendered yet, so the item is hidden.
208 * The page is opened from the Tools page instead of its own menu item.
209 *
210 * @return void
211 */
212 public function remove_menu_item() {
213 \remove_submenu_page( 'wpseo_dashboard', self::PAGE );
214 }
215
216 /**
217 * Adds the page to the (currently) last position in the array.
218 *
219 * @param array<array<string|callable|null>> $pages The pages.
220 *
221 * @return array<array<string|callable|null>> The pages.
222 */
223 public function add_page( $pages ) {
224 $pages[] = [
225 'wpseo_dashboard',
226 '',
227 \__( 'Bulk editor', 'wordpress-seo' ),
228 'wpseo_manage_options',
229 self::PAGE,
230 [ $this, 'display_page' ],
231 ];
232
233 return $pages;
234 }
235
236 /**
237 * Displays the page.
238 *
239 * @return void
240 */
241 public function display_page() {
242 echo '<div id="yoast-seo-bulk-editor"></div>';
243 }
244
245 /**
246 * Enqueues the assets.
247 *
248 * @return void
249 */
250 public function enqueue_assets() {
251 // Remove the emoji script as it is incompatible with both React and any contenteditable fields.
252 \remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
253 $this->asset_manager->enqueue_script( self::ASSETS_NAME );
254 $this->asset_manager->enqueue_style( self::ASSETS_NAME );
255 $this->asset_manager->localize_script( self::ASSETS_NAME, 'wpseoBulkEditorData', $this->get_script_data() );
256 }
257
258 /**
259 * Creates the script data.
260 *
261 * @return array<string, string|array<string, string|bool>|array<array<string, string>>> The script data.
262 */
263 public function get_script_data() {
264 $content_types = $this->content_types_repository->get_content_types();
265 $is_premium = $this->product_helper->is_premium();
266 $is_version_supported = $this->is_premium_version_supported( $is_premium );
267
268 return [
269 'contentTypes' => $content_types,
270 'endpoints' => $this->endpoints_repository->get_all_endpoints()->to_array(),
271 // These must stay server-generated URLs: the bulk editor assigns them to window.location.href for its
272 // "Back to Tools" / logo navigation. If a link ever derives from request input, validate it with
273 // wp_validate_redirect() here before exposing it, to avoid an open redirect on the front-end.
274 'links' => [
275 'dashboard' => \admin_url( 'admin.php?page=' . General_Page_Integration::PAGE ),
276 'tools' => \admin_url( 'admin.php?page=wpseo_tools' ),
277 ],
278 'nonce' => $this->nonce_repository->get_rest_nonce(),
279 'restRoot' => \esc_url_raw( \rest_url() ),
280 'preferences' => [
281 'isPremium' => $is_premium,
282 'isPremiumVersionSupported' => $is_version_supported,
283 'isAiEnabled' => $this->options_helper->get( 'enable_ai_generator' ) === true,
284 'isRtl' => \is_rtl(),
285 'pluginUrl' => \plugins_url( '', \WPSEO_FILE ),
286 'premiumUpdateUrl' => $this->get_premium_update_url(),
287 ],
288 'linkParams' => $this->short_link_helper->get_query_params(),
289 'analysis' => [
290 'contentLocale' => \get_locale(),
291 // Re-scoring only runs when SEO analysis is enabled, matching the post editor.
292 'keywordAnalysisActive' => $this->options_helper->get( 'keyword_analysis_active' ) === true,
293 // Used when collecting the AI prompt content, so shortcode delimiters are stripped from the
294 // text while the content they enclose is kept. Not gated on SEO analysis being enabled: the
295 // prompt content is collected for AI suggestions, which do not depend on the analysis.
296 'shortcodes' => $this->get_valid_shortcode_tags(),
297 ],
298 'optInNotificationSeen' => [
299 'bulk_editor_tour' => $this->is_tour_opt_in_notification_seen(),
300 ],
301 'initialSelection' => $this->get_initial_selection( $content_types ),
302 'myyoastConnection' => $this->myyoast_connection_data_presenter->present(),
303 'replacementVariables' => $this->get_replacement_variables(),
304 ];
305 }
306
307 /**
308 * Builds the replacement variable data passed to the JS editor.
309 *
310 * Mirrors Settings_Integration::get_replacement_variables() so the bulk editor's
311 * ReplacementVariableEditor receives the same variable metadata as the settings page.
312 *
313 * @return array{variables: array<int, array<string, string|bool>>, recommended: array<string, string[]>, specific: array<string, string[]>, shared: string[]} The replacement variable data.
314 */
315 private function get_replacement_variables(): array {
316 $recommended_replace_vars = new WPSEO_Admin_Recommended_Replace_Vars();
317 $specific_replace_vars = new WPSEO_Admin_Editor_Specific_Replace_Vars();
318 $replacement_variables = $this->replace_vars->get_replacement_variables_with_labels();
319
320 return [
321 'variables' => $replacement_variables,
322 'recommended' => $recommended_replace_vars->get_recommended_replacevars(),
323 'specific' => $specific_replace_vars->get(),
324 'shared' => $specific_replace_vars->get_generic( $replacement_variables ),
325 ];
326 }
327
328 /**
329 * Checks whether the installed Premium version is compatible with the current Free plugin.
330 *
331 * @param bool $is_premium Whether Premium is the currently active plugin.
332 *
333 * @return bool False when Premium needs upgrading or not active.
334 */
335 private function is_premium_version_supported( bool $is_premium ): bool {
336 if ( ! $is_premium ) {
337 return false;
338 }
339
340 $premium_version = $this->product_helper->get_premium_version();
341
342 if ( $premium_version === null ) {
343 return false;
344 }
345
346 return \version_compare( $premium_version, '28.1-RC0', '>' );
347 }
348
349 /**
350 * Returns the one-click Premium update URL for the current user, or an empty string when the user
351 * lacks the `update_plugins` capability (and would hit a wp_die permission error on update.php).
352 *
353 * @return string The nonce-protected update URL, or an empty string.
354 */
355 private function get_premium_update_url(): string {
356 if ( ! \current_user_can( 'update_plugins' ) ) {
357 return '';
358 }
359
360 return \html_entity_decode(
361 \wp_nonce_url(
362 \self_admin_url( 'update.php?action=upgrade-plugin&plugin=wordpress-seo-premium%2Fwp-seo-premium.php' ),
363 'upgrade-plugin_wordpress-seo-premium/wp-seo-premium.php',
364 ),
365 \ENT_COMPAT,
366 );
367 }
368
369 /**
370 * Returns the selection carried over from a post overview bulk action, if any.
371 *
372 * The parameters only decide which rows start out selected in the app; the REST endpoints
373 * enforce the actual per-post edit access when anything is saved.
374 *
375 * @param array<array<string, string>> $content_types The available content types.
376 *
377 * @return array<string, string|int|array<int>> The content type, post IDs and overview selection count.
378 */
379 private function get_initial_selection( array $content_types ): array {
380 $initial_selection = [
381 'contentType' => '',
382 'postIds' => [],
383 'selectedCount' => 0,
384 ];
385
386 // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Reason: read-only display state, no action is taken.
387 if ( ! isset( $_GET[ self::CONTENT_TYPE_PARAM ] ) || ! \is_string( $_GET[ self::CONTENT_TYPE_PARAM ] ) ) {
388 return $initial_selection;
389 }
390
391 $content_type = \sanitize_text_field( \wp_unslash( $_GET[ self::CONTENT_TYPE_PARAM ] ) );
392 if ( ! \in_array( $content_type, \array_column( $content_types, 'name' ), true ) ) {
393 return $initial_selection;
394 }
395 $initial_selection['contentType'] = $content_type;
396
397 if ( isset( $_GET[ self::POST_IDS_PARAM ] ) && \is_string( $_GET[ self::POST_IDS_PARAM ] ) ) {
398 $post_ids = \explode( ',', \sanitize_text_field( \wp_unslash( $_GET[ self::POST_IDS_PARAM ] ) ) );
399 $post_ids = \array_values(
400 \array_unique(
401 \array_filter(
402 \array_map( 'intval', $post_ids ),
403 static function ( $id ) {
404 return $id > 0;
405 },
406 ),
407 ),
408 );
409 $post_ids = \array_slice( $post_ids, 0, Batch_Limit::MAX_ITEMS );
410
411 $initial_selection['postIds'] = $post_ids;
412 $initial_selection['selectedCount'] = \count( $post_ids );
413 }
414
415 if (
416 $initial_selection['postIds'] !== []
417 && isset( $_GET[ self::SELECTED_COUNT_PARAM ] )
418 && \is_string( $_GET[ self::SELECTED_COUNT_PARAM ] )
419 ) {
420 // The count can only grow beyond the carried IDs, never shrink below them.
421 $initial_selection['selectedCount'] = \max(
422 $initial_selection['selectedCount'],
423 \absint( \wp_unslash( $_GET[ self::SELECTED_COUNT_PARAM ] ) ),
424 );
425 }
426 // phpcs:enable WordPress.Security.NonceVerification.Recommended
427
428 return $initial_selection;
429 }
430
431 /**
432 * Registers the carried-over selection parameters as removable, so WordPress cleans them from the
433 * address bar once the page has picked them up.
434 *
435 * @param array<string> $removable_query_args The removable query args.
436 *
437 * @return array<string> The removable query args.
438 */
439 public function add_removable_query_args( $removable_query_args ) {
440 $removable_query_args[] = self::POST_IDS_PARAM;
441 $removable_query_args[] = self::SELECTED_COUNT_PARAM;
442
443 return $removable_query_args;
444 }
445
446 /**
447 * Gets whether the bulk editor guided tour has been seen by the current user.
448 *
449 * @return bool True when the tour has been seen, false otherwise.
450 */
451 private function is_tour_opt_in_notification_seen(): bool {
452 $current_user_id = $this->user_helper->get_current_user_id();
453
454 return (bool) $this->user_helper->get_meta( $current_user_id, '_yoast_wpseo_bulk_editor_tour_opt_in_notification_seen', true );
455 }
456
457 /**
458 * Returns the tags of all registered shortcodes.
459 *
460 * Mirrors what the post editor passes to the analysis (see WPSEO_Metabox::get_valid_shortcode_tags()), so the
461 * parse tree treats shortcodes the same on both pages: the delimiters are removed and the text an enclosing
462 * shortcode wraps is kept. Without this list the raw brackets stay in the text and consume prompt tokens.
463 *
464 * @return array<string> The registered shortcode tags.
465 */
466 private function get_valid_shortcode_tags(): array {
467 // The global is always set by WordPress, but stay defensive: an empty list only costs shortcode parity.
468 if ( ! isset( $GLOBALS['shortcode_tags'] ) || ! \is_array( $GLOBALS['shortcode_tags'] ) ) {
469 return [];
470 }
471
472 return \array_keys( $GLOBALS['shortcode_tags'] );
473 }
474
475 /**
476 * Removes all current WP notices.
477 *
478 * @return void
479 */
480 public function remove_notices() {
481 \remove_all_actions( 'admin_notices' );
482 \remove_all_actions( 'user_admin_notices' );
483 \remove_all_actions( 'network_admin_notices' );
484 \remove_all_actions( 'all_admin_notices' );
485 }
486 }
487