PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 28.2
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v28.2
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 / inc / class-wpseo-meta.php

class-wpseo-meta.php in Yoast SEO – Advanced SEO with real-time guidance and built-in AI 28.2, at inc/class-wpseo-meta.php

1,111 lines 36.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * WPSEO plugin file.
4 *
5 * @package WPSEO\Internals
6 * @since 1.5.0
7 */
8
9 use Yoast\WP\SEO\Config\Schema_Types;
10 use Yoast\WP\SEO\Helpers\Schema\Article_Helper;
11 use Yoast\WP\SEO\Repositories\Indexable_Repository;
12
13 /**
14 * This class implements defaults and value validation for all WPSEO Post Meta values.
15 *
16 * Some guidelines:
17 * - To update a meta value, you can just use update_post_meta() with the full (prefixed) meta key
18 * or the convenience method WPSEO_Meta::set_value() with the internal key.
19 * All updates will be automatically validated.
20 * Meta values will only be saved to the database if they are *not* the same as the default to
21 * keep database load low.
22 * - To retrieve a WPSEO meta value, you **must** use WPSEO_Meta::get_value() which will always return a
23 * string value, either the saved value or the default.
24 * This method can also retrieve a complete set of WPSEO meta values for one specific post, see
25 * the method documentation for the parameters.
26 *
27 * {@internal Unfortunately there isn't a filter available to hook into before returning the results
28 * for get_post_meta(), get_post_custom() and the likes. That would have been the
29 * preferred solution.}}
30 *
31 * {@internal All WP native get_meta() results get cached internally, so no need to cache locally.}}
32 * {@internal Use $key when the key is the WPSEO internal name (without prefix), $meta_key when it
33 * includes the prefix.}}
34 */
35 class WPSEO_Meta {
36
37 /**
38 * Prefix for all WPSEO meta values in the database.
39 *
40 * {@internal If at any point this would change, quite apart from an upgrade routine,
41 * this also will need to be changed in the wpml-config.xml file.}}
42 *
43 * @var string
44 */
45 public static $meta_prefix = '_yoast_wpseo_';
46
47 /**
48 * Prefix for all WPSEO meta value form field names and ids.
49 *
50 * @var string
51 */
52 public static $form_prefix = 'yoast_wpseo_';
53
54 /**
55 * Allowed length of the meta description.
56 *
57 * @var int
58 */
59 public static $meta_length = 156;
60
61 /**
62 * Reason the meta description is not the default length.
63 *
64 * @var string
65 */
66 public static $meta_length_reason = '';
67
68 /**
69 * Meta box field definitions for the meta box form.
70 *
71 * {@internal
72 * - Titles, help texts, description text and option labels are added via a translate_meta_boxes() method
73 * in the relevant child classes (WPSEO_Metabox and WPSEO_Social_admin) as they are only needed there.
74 * - Beware: even though the meta keys are divided into subsets, they still have to be uniquely named!}}
75 *
76 * @var array
77 * Array format:
78 * (required) 'type' => (string) field type. i.e. text / textarea / checkbox /
79 * radio / select / multiselect / upload etc.
80 * (recommended) 'default_value' => (string|array) default value for the field.
81 * IMPORTANT:
82 * - if the field has options, the default has to be the
83 * key of one of the options.
84 * - if the field is a text field, the default **has** to be
85 * an empty string as otherwise the user can't save
86 * an empty value/delete the meta value.
87 * - if the field is a checkbox, the only valid values
88 * are 'on' or 'off'.
89 * (semi-required) 'options' => (array) options for used with (multi-)select and radio
90 * fields, required if that's the field type.
91 * key = (string) value which will be saved to db.
92 * value = (string) text label for the option.
93 * (optional) 'autocomplete' => (bool) whether autocomplete is on for text fields,
94 * defaults to true.
95 * (optional) 'class' => (string) classname(s) to add to the actual <input> tag.
96 * (optional) 'rows' => (int) number of rows for a textarea, defaults to 3.
97 * (optional) 'serialized' => (bool) whether the value is expected to be serialized,
98 * i.e. an array or object, defaults to false.
99 * Currently only used by add-on plugins.
100 */
101 public static $meta_fields = [
102 'general' => [
103 'focuskw' => [
104 'type' => 'hidden',
105 'title' => '',
106 'show_in_rest' => true,
107 'single' => true,
108 ],
109 'title' => [
110 'type' => 'hidden',
111 'default_value' => '',
112 'show_in_rest' => true,
113 'single' => true,
114 ],
115 'metadesc' => [
116 'type' => 'hidden',
117 'default_value' => '',
118 'class' => 'metadesc',
119 'rows' => 2,
120 'show_in_rest' => true,
121 'single' => true,
122 ],
123 'linkdex' => [
124 'type' => 'hidden',
125 'default_value' => '0',
126 ],
127 'content_score' => [
128 'type' => 'hidden',
129 'default_value' => '0',
130 ],
131 'inclusive_language_score' => [
132 'type' => 'hidden',
133 'default_value' => '0',
134 ],
135 'is_cornerstone' => [
136 'type' => 'hidden',
137 'default_value' => 'false',
138 ],
139 ],
140 'advanced' => [
141 'meta-robots-noindex' => [
142 'type' => 'hidden',
143 'default_value' => '0', // = post-type default.
144 'options' => [
145 '0' => '', // Post type default.
146 '2' => '', // Index.
147 '1' => '', // No-index.
148 ],
149 ],
150 'meta-robots-nofollow' => [
151 'type' => 'hidden',
152 'default_value' => '0', // = follow.
153 'options' => [
154 '0' => '', // Follow.
155 '1' => '', // No-follow.
156 ],
157 ],
158 'meta-robots-adv' => [
159 'type' => 'hidden',
160 'default_value' => '',
161 'options' => [
162 'noimageindex' => '',
163 'noarchive' => '',
164 'nosnippet' => '',
165 ],
166 ],
167 'bctitle' => [
168 'type' => 'hidden',
169 'default_value' => '',
170 ],
171 'canonical' => [
172 'type' => 'hidden',
173 'default_value' => '',
174 ],
175 'redirect' => [
176 'type' => 'url',
177 'default_value' => '',
178 ],
179 ],
180 'social' => [],
181 'schema' => [
182 'schema_page_type' => [
183 'type' => 'hidden',
184 'options' => Schema_Types::PAGE_TYPES,
185 ],
186 'schema_article_type' => [
187 'type' => 'hidden',
188 'hide_on_pages' => true,
189 'options' => Schema_Types::ARTICLE_TYPES,
190 ],
191 ],
192 /* Fields we should validate & save, but not show on any form. */
193 'non_form' => [
194 'linkdex' => [
195 'type' => null,
196 'default_value' => '0',
197 ],
198 ],
199 'content_planner' => [
200 'is_content_planner_banner_rendered' => [
201 'type' => 'hidden',
202 'default_value' => '0',
203 ],
204 'is_content_planner_banner_dismissed' => [
205 'type' => 'hidden',
206 'default_value' => '0',
207 ],
208 ],
209 ];
210
211 /**
212 * Helper property - reverse index of the definition array.
213 *
214 * Format: [full meta key including prefix] => array
215 * ['subset'] => (string) primary index
216 * ['key'] => (string) internal key
217 *
218 * @var array
219 */
220 public static $fields_index = [];
221
222 /**
223 * Helper property - array containing only the defaults in the format:
224 * [full meta key including prefix] => (string) default value
225 *
226 * @var array
227 */
228 public static $defaults = [];
229
230 /**
231 * Helper property to define the social network meta field definitions - networks.
232 *
233 * @var array
234 */
235 private static $social_networks = [
236 'opengraph' => 'opengraph',
237 'twitter' => 'twitter',
238 ];
239
240 /**
241 * Helper property to define the social network meta field definitions - fields and their type.
242 *
243 * @var array
244 */
245 private static $social_fields = [
246 'title' => 'hidden',
247 'description' => 'hidden',
248 'image' => 'hidden',
249 'image-id' => 'hidden',
250 ];
251
252 /**
253 * Register our actions and filters.
254 *
255 * @return void
256 */
257 public static function init() {
258 foreach ( self::$social_networks as $option => $network ) {
259 if ( WPSEO_Options::get( $option, false, [ 'wpseo_social' ] ) === true ) {
260 foreach ( self::$social_fields as $box => $type ) {
261 self::$meta_fields['social'][ $network . '-' . $box ] = [
262 'type' => $type,
263 'default_value' => '',
264 ];
265 }
266 }
267 }
268 unset( $option, $network, $box, $type );
269
270 /**
271 * Allow add-on plugins to register their meta fields for management by this class.
272 * Calls to add_filter() must be made before plugins_loaded prio 14.
273 */
274 $extra_fields = apply_filters( 'add_extra_wpseo_meta_fields', [] );
275 if ( is_array( $extra_fields ) ) {
276 self::$meta_fields = self::array_merge_recursive_distinct( $extra_fields, self::$meta_fields );
277 }
278 unset( $extra_fields );
279
280 foreach ( self::$meta_fields as $subset => $field_group ) {
281 foreach ( $field_group as $key => $field_def ) {
282
283 // Register for all post types: sanitise callback only, REST disabled.
284 register_meta(
285 'post',
286 self::$meta_prefix . $key,
287 [ 'sanitize_callback' => [ self::class, 'sanitize_post_meta' ] ],
288 );
289
290 // Re-register for the 'post' subtype with REST exposure and auth callback when show_in_rest is enabled.
291 if ( ! empty( $field_def['show_in_rest'] ) ) {
292 register_meta(
293 'post',
294 self::$meta_prefix . $key,
295 [
296 'show_in_rest' => true,
297 'single' => ( $field_def['single'] ?? false ),
298 'type' => 'string',
299 'object_subtype' => 'post',
300 'sanitize_callback' => [ self::class, 'sanitize_post_meta' ],
301 'auth_callback' => static function ( $allowed, $meta_key, $object_id ) {
302 return current_user_can( 'edit_post', $object_id );
303 },
304 ],
305 );
306 }
307
308 // Set the $fields_index property for efficiency.
309 self::$fields_index[ self::$meta_prefix . $key ] = [
310 'subset' => $subset,
311 'key' => $key,
312 ];
313
314 // Set the $defaults property for efficiency.
315 if ( isset( $field_def['default_value'] ) ) {
316 self::$defaults[ self::$meta_prefix . $key ] = $field_def['default_value'];
317 }
318 else {
319 // Meta will always be a string, so let's make the meta meta default also a string.
320 self::$defaults[ self::$meta_prefix . $key ] = '';
321 }
322 }
323 }
324 unset( $subset, $field_group, $key, $field_def );
325
326 // Strip meta fields that have show_in_rest enabled from REST responses for users
327 // without edit_post capability. register_meta's auth_callback only covers writes,
328 // so read access must be restricted separately via this filter.
329 // Register only for 'post' post type. Other post types don't expose these fields.
330 add_filter( 'rest_prepare_post', [ self::class, 'hide_meta_from_unauthorized_rest_response' ], 10, 2 );
331
332 self::filter_schema_article_types();
333
334 add_filter( 'update_post_metadata', [ self::class, 'remove_meta_if_default' ], 10, 5 );
335 add_filter( 'add_post_metadata', [ self::class, 'dont_save_meta_if_default' ], 10, 4 );
336 }
337
338 /**
339 * Retrieve the meta box form field definitions for the given tab and post type.
340 *
341 * @param string $tab Tab for which to retrieve the field definitions.
342 * @param string $post_type Post type of the current post.
343 *
344 * @return array Array containing the meta box field definitions.
345 */
346 public static function get_meta_field_defs( $tab, $post_type = 'post' ) {
347 if ( ! isset( self::$meta_fields[ $tab ] ) ) {
348 return [];
349 }
350
351 $field_defs = self::$meta_fields[ $tab ];
352
353 switch ( $tab ) {
354 case 'non-form':
355 // Prevent non-form fields from being passed to forms.
356 $field_defs = [];
357 break;
358
359 case 'advanced':
360 global $post;
361
362 if ( ! WPSEO_Capability_Utils::current_user_can( 'wpseo_edit_advanced_metadata' ) && WPSEO_Options::get( 'disableadvanced_meta' ) ) {
363 return [];
364 }
365
366 $post_type = '';
367 if ( isset( $post->post_type ) ) {
368 $post_type = $post->post_type;
369 }
370 elseif ( ! isset( $post->post_type ) && isset( $_GET['post_type'] ) ) {
371 $post_type = sanitize_text_field( $_GET['post_type'] );
372 }
373
374 if ( $post_type === '' ) {
375 return [];
376 }
377
378 /* Don't show the breadcrumb title field if breadcrumbs aren't enabled. */
379 if ( WPSEO_Options::get( 'breadcrumbs-enable', false ) !== true && ! current_theme_supports( 'yoast-seo-breadcrumbs' ) ) {
380 unset( $field_defs['bctitle'] );
381 }
382
383 if ( empty( $post->ID ) || ( ! empty( $post->ID ) && self::get_value( 'redirect', $post->ID ) === '' ) ) {
384 unset( $field_defs['redirect'] );
385 }
386 break;
387
388 case 'schema':
389 if ( ! WPSEO_Capability_Utils::current_user_can( 'wpseo_edit_advanced_metadata' ) && WPSEO_Options::get( 'disableadvanced_meta' ) ) {
390 return [];
391 }
392
393 $field_defs['schema_page_type']['default'] = WPSEO_Options::get( 'schema-page-type-' . $post_type );
394
395 $article_helper = new Article_Helper();
396 if ( $article_helper->is_article_post_type( $post_type ) ) {
397 $default_schema_article_type = WPSEO_Options::get( 'schema-article-type-' . $post_type );
398
399 /** This filter is documented in inc/options/class-wpseo-option-titles.php */
400 $allowed_article_types = apply_filters( 'wpseo_schema_article_types', Schema_Types::ARTICLE_TYPES );
401
402 if ( ! array_key_exists( $default_schema_article_type, $allowed_article_types ) ) {
403 $default_schema_article_type = WPSEO_Options::get_default( 'wpseo_titles', 'schema-article-type-' . $post_type );
404 }
405 $field_defs['schema_article_type']['default'] = $default_schema_article_type;
406 }
407 else {
408 unset( $field_defs['schema_article_type'] );
409 }
410
411 break;
412 }
413
414 /**
415 * Filter the WPSEO metabox form field definitions for a tab.
416 * {tab} can be 'general', 'advanced' or 'social'.
417 *
418 * @param array $field_defs Metabox form field definitions.
419 * @param string $post_type Post type of the post the metabox is for, defaults to 'post'.
420 *
421 * @return array
422 */
423 return apply_filters( 'wpseo_metabox_entries_' . $tab, $field_defs, $post_type );
424 }
425
426 /**
427 * Validate the post meta values.
428 *
429 * @param mixed $meta_value The new value.
430 * @param string $meta_key The full meta key (including prefix).
431 *
432 * @return string Validated meta value.
433 */
434 public static function sanitize_post_meta( $meta_value, $meta_key ) {
435 $field_def = self::$meta_fields[ self::$fields_index[ $meta_key ]['subset'] ][ self::$fields_index[ $meta_key ]['key'] ];
436 $clean = self::$defaults[ $meta_key ];
437
438 switch ( true ) {
439 case ( $meta_key === self::$meta_prefix . 'linkdex' ):
440 $int = WPSEO_Utils::validate_int( $meta_value );
441 if ( $int !== false && $int >= 0 ) {
442 $clean = (string) $int; // Convert to string to make sure default check works.
443 }
444 break;
445
446 case ( $field_def['type'] === 'checkbox' ):
447 // Only allow value if it's one of the predefined options.
448 if ( in_array( $meta_value, [ 'on', 'off' ], true ) ) {
449 $clean = $meta_value;
450 }
451 break;
452
453 case ( $field_def['type'] === 'select' || $field_def['type'] === 'radio' ):
454 // Only allow value if it's one of the predefined options.
455 if ( isset( $field_def['options'][ $meta_value ] ) ) {
456 $clean = $meta_value;
457 }
458 break;
459
460 case ( $field_def['type'] === 'hidden' && $meta_key === self::$meta_prefix . 'meta-robots-adv' ):
461 $clean = self::validate_meta_robots_adv( $meta_value );
462 break;
463
464 case ( $field_def['type'] === 'url' || $meta_key === self::$meta_prefix . 'canonical' ):
465 // Validate as url(-part).
466 $url = WPSEO_Utils::sanitize_url( $meta_value );
467 if ( $url !== '' ) {
468 $clean = $url;
469 }
470 break;
471
472 case ( $field_def['type'] === 'upload' && in_array( $meta_key, [ self::$meta_prefix . 'opengraph-image', self::$meta_prefix . 'twitter-image' ], true ) ):
473 // Validate as url.
474 $url = WPSEO_Utils::sanitize_url( $meta_value, [ 'http', 'https', 'ftp', 'ftps' ] );
475 if ( $url !== '' ) {
476 $clean = $url;
477 }
478 break;
479
480 case ( $field_def['type'] === 'hidden' && $meta_key === self::$meta_prefix . 'is_cornerstone' ):
481 $clean = $meta_value;
482
483 /*
484 * This used to be a checkbox, then became a hidden input.
485 * To make sure the value remains consistent, we cast 'true' to '1'.
486 */
487 if ( $meta_value === 'true' ) {
488 $clean = '1';
489 }
490 break;
491
492 case ( $field_def['type'] === 'hidden' && isset( $field_def['options'] ) ):
493 // Only allow value if it's one of the predefined options.
494 if ( isset( $field_def['options'][ $meta_value ] ) ) {
495 $clean = $meta_value;
496 }
497 break;
498
499 case ( $field_def['type'] === 'textarea' ):
500 if ( is_string( $meta_value ) ) {
501 // Remove line breaks and tabs.
502 // @todo [JRF => Yoast] Verify that line breaks and the likes aren't allowed/recommended in meta header fields.
503 $meta_value = str_replace( [ "\n", "\r", "\t", ' ' ], ' ', $meta_value );
504 $clean = WPSEO_Utils::sanitize_text_field( trim( $meta_value ) );
505 }
506 break;
507
508 case ( $field_def['type'] === 'multiselect' ):
509 $clean = $meta_value;
510 break;
511
512 case ( $field_def['type'] === 'text' ):
513 default:
514 if ( is_string( $meta_value ) ) {
515 $clean = WPSEO_Utils::sanitize_text_field( trim( $meta_value ) );
516 }
517
518 break;
519 }
520
521 $clean = apply_filters( 'wpseo_sanitize_post_meta_' . $meta_key, $clean, $meta_value, $field_def, $meta_key );
522
523 return $clean;
524 }
525
526 /**
527 * Validate a meta-robots-adv meta value.
528 *
529 * @todo [JRF => Yoast] Verify that this logic for the prioritisation is correct.
530 *
531 * @param array|string $meta_value The value to validate.
532 *
533 * @return string Clean value.
534 */
535 public static function validate_meta_robots_adv( $meta_value ) {
536 $clean = self::$meta_fields['advanced']['meta-robots-adv']['default_value'];
537 $options = self::$meta_fields['advanced']['meta-robots-adv']['options'];
538
539 if ( is_string( $meta_value ) ) {
540 $meta_value = explode( ',', $meta_value );
541 }
542
543 if ( is_array( $meta_value ) && $meta_value !== [] ) {
544 $meta_value = array_map( 'trim', $meta_value );
545
546 // Individual selected entries.
547 $cleaning = [];
548 foreach ( $meta_value as $value ) {
549 if ( isset( $options[ $value ] ) ) {
550 $cleaning[] = $value;
551 }
552 }
553
554 if ( $cleaning !== [] ) {
555 $clean = implode( ',', $cleaning );
556 }
557 unset( $cleaning, $value );
558 }
559
560 return $clean;
561 }
562
563 /**
564 * Prevent saving of default values and remove potential old value from the database if replaced by a default.
565 *
566 * @param bool $check The current status to allow updating metadata for the given type.
567 * @param int $object_id ID of the current object for which the meta is being updated.
568 * @param string $meta_key The full meta key (including prefix).
569 * @param string $meta_value New meta value.
570 * @param string $prev_value The old meta value.
571 *
572 * @return bool|null True = stop saving, null = continue saving.
573 */
574 public static function remove_meta_if_default( $check, $object_id, $meta_key, $meta_value, $prev_value = '' ) {
575 /* If it's one of our meta fields, check against default. */
576 if ( isset( self::$fields_index[ $meta_key ] ) && self::meta_value_is_default( $meta_key, $meta_value ) === true ) {
577 if ( $prev_value !== '' ) {
578 delete_post_meta( $object_id, $meta_key, $prev_value );
579 }
580 else {
581 delete_post_meta( $object_id, $meta_key );
582 }
583
584 return true; // Stop saving the value.
585 }
586
587 return $check; // Go on with the normal execution (update) in meta.php.
588 }
589
590 /**
591 * Prevent adding of default values to the database.
592 *
593 * @param bool $check The current status to allow adding metadata for the given type.
594 * @param int $object_id ID of the current object for which the meta is being added.
595 * @param string $meta_key The full meta key (including prefix).
596 * @param string $meta_value New meta value.
597 *
598 * @return bool|null True = stop saving, null = continue saving.
599 */
600 public static function dont_save_meta_if_default( $check, $object_id, $meta_key, $meta_value ) {
601 /* If it's one of our meta fields, check against default. */
602 if ( isset( self::$fields_index[ $meta_key ] ) && self::meta_value_is_default( $meta_key, $meta_value ) === true ) {
603 return true; // Stop saving the value.
604 }
605
606 return $check; // Go on with the normal execution (add) in meta.php.
607 }
608
609 /**
610 * Is the given meta value the same as the default value ?
611 *
612 * @param string $meta_key The full meta key (including prefix).
613 * @param mixed $meta_value The value to check.
614 *
615 * @return bool
616 */
617 public static function meta_value_is_default( $meta_key, $meta_value ) {
618 return ( isset( self::$defaults[ $meta_key ] ) && $meta_value === self::$defaults[ $meta_key ] );
619 }
620
621 /**
622 * Get a custom post meta value.
623 *
624 * Returns the default value if the meta value has not been set.
625 *
626 * {@internal Unfortunately there isn't a filter available to hook into before returning
627 * the results for get_post_meta(), get_post_custom() and the likes. That
628 * would have been the preferred solution.}}
629 *
630 * @param string $key Internal key of the value to get (without prefix).
631 * @param int $postid Post ID of the post to get the value for.
632 *
633 * @return string All 'normal' values returned from get_post_meta() are strings.
634 * Objects and arrays are possible, but not used by this plugin
635 * and therefore discarted (except when the special 'serialized' field def
636 * value is set to true - only used by add-on plugins for now).
637 * Will return the default value if no value was found.
638 * Will return empty string if no default was found (not one of our keys) or
639 * if the post does not exist.
640 */
641 public static function get_value( $key, $postid = 0 ) {
642 global $post;
643
644 $postid = absint( $postid );
645 if ( $postid === 0 ) {
646 if ( ( isset( $post ) && is_object( $post ) ) && ( isset( $post->post_status ) && $post->post_status !== 'auto-draft' ) ) {
647 $postid = $post->ID;
648 }
649 else {
650 return '';
651 }
652 }
653
654 $custom = get_post_custom( $postid ); // Array of strings or empty array.
655 $table_key = self::$meta_prefix . $key;
656
657 // Populate the field_def using the field_index lookup array.
658 $field_def = [];
659 if ( isset( self::$fields_index[ $table_key ] ) ) {
660 $field_def = self::$meta_fields[ self::$fields_index[ $table_key ]['subset'] ][ self::$fields_index[ $table_key ]['key'] ];
661 }
662
663 // Check if we have a custom post meta entry.
664 if ( isset( $custom[ $table_key ][0] ) ) {
665 $unserialized = maybe_unserialize( $custom[ $table_key ][0] );
666
667 // Check if it is already unserialized.
668 if ( $custom[ $table_key ][0] === $unserialized ) {
669 return $custom[ $table_key ][0];
670 }
671
672 // Check whether we need to unserialize it.
673 if ( isset( $field_def['serialized'] ) && $field_def['serialized'] === true ) {
674 // Ok, serialize value expected/allowed.
675 return $unserialized;
676 }
677 }
678
679 // Meta was either not found or found, but object/array while not allowed to be.
680 if ( isset( self::$defaults[ self::$meta_prefix . $key ] ) ) {
681 // Update the default value to the current post type.
682 switch ( $key ) {
683 case 'schema_page_type':
684 case 'schema_article_type':
685 return '';
686 }
687
688 return self::$defaults[ self::$meta_prefix . $key ];
689 }
690
691 /*
692 * Shouldn't ever happen, means not one of our keys as there will always be a default available
693 * for all our keys.
694 */
695 return '';
696 }
697
698 /**
699 * Update a meta value for a post.
700 *
701 * @param string $key The internal key of the meta value to change (without prefix).
702 * @param mixed $meta_value The value to set the meta to.
703 * @param int $post_id The ID of the post to change the meta for.
704 *
705 * @return bool Whether the value was changed.
706 */
707 public static function set_value( $key, $meta_value, $post_id ) {
708 /*
709 * Slash the data, because `update_metadata` will unslash it and we have already unslashed it.
710 * Related issue: https://github.com/Yoast/YoastSEO.js/issues/2158
711 */
712 $meta_value = wp_slash( $meta_value );
713
714 return update_post_meta( $post_id, self::$meta_prefix . $key, $meta_value );
715 }
716
717 /**
718 * Deletes a meta value for a post.
719 *
720 * @param string $key The internal key of the meta value to change (without prefix).
721 * @param int $post_id The ID of the post to delete the meta for.
722 *
723 * @return bool Whether the delete was successful or not.
724 */
725 public static function delete( $key, $post_id ) {
726 return delete_post_meta( $post_id, self::$meta_prefix . $key );
727 }
728
729 /**
730 * Used for imports, this functions imports the value of $old_metakey into $new_metakey for those post
731 * where no WPSEO meta data has been set.
732 * Optionally deletes the $old_metakey values.
733 *
734 * @param string $old_metakey The old key of the meta value.
735 * @param string $new_metakey The new key, usually the WPSEO meta key (including prefix).
736 * @param bool $delete_old Whether to delete the old meta key/value-sets.
737 *
738 * @return void
739 */
740 public static function replace_meta( $old_metakey, $new_metakey, $delete_old = false ) {
741 global $wpdb;
742
743 /*
744 * Get only those rows where no wpseo meta values exist for the same post
745 * (with the exception of linkdex as that will be set independently of whether the post has been edited).
746 *
747 * {@internal Query is pretty well optimized this way.}}
748 */
749 $query = $wpdb->prepare(
750 "
751 SELECT `a`.*
752 FROM {$wpdb->postmeta} AS a
753 WHERE `a`.`meta_key` = %s
754 AND NOT EXISTS (
755 SELECT DISTINCT `post_id` , count( `meta_id` ) AS count
756 FROM {$wpdb->postmeta} AS b
757 WHERE `a`.`post_id` = `b`.`post_id`
758 AND `meta_key` LIKE %s
759 AND `meta_key` <> %s
760 GROUP BY `post_id`
761 )
762 ;",
763 $old_metakey,
764 $wpdb->esc_like( self::$meta_prefix . '%' ),
765 self::$meta_prefix . 'linkdex',
766 );
767 $oldies = $wpdb->get_results( $query );
768
769 if ( is_array( $oldies ) && $oldies !== [] ) {
770 foreach ( $oldies as $old ) {
771 update_post_meta( $old->post_id, $new_metakey, $old->meta_value );
772 }
773 }
774
775 // Delete old keys.
776 if ( $delete_old === true ) {
777 delete_post_meta_by_key( $old_metakey );
778 }
779 }
780
781 /**
782 * General clean-up of the saved meta values.
783 * - Remove potentially lingering old meta keys;
784 * - Remove all default and invalid values.
785 *
786 * @return void
787 */
788 public static function clean_up() {
789 global $wpdb;
790
791 /*
792 * Clean up '_yoast_wpseo_meta-robots'.
793 *
794 * Retrieve all '_yoast_wpseo_meta-robots' meta values and convert if no new values found.
795 *
796 * {@internal Query is pretty well optimized this way.}}
797 *
798 * @todo [JRF => Yoast] Find out all possible values which the old '_yoast_wpseo_meta-robots' could contain
799 * to convert the data correctly.
800 */
801 $query = $wpdb->prepare(
802 "
803 SELECT `a`.*
804 FROM {$wpdb->postmeta} AS a
805 WHERE `a`.`meta_key` = %s
806 AND NOT EXISTS (
807 SELECT DISTINCT `post_id` , count( `meta_id` ) AS count
808 FROM {$wpdb->postmeta} AS b
809 WHERE `a`.`post_id` = `b`.`post_id`
810 AND ( `meta_key` = %s
811 OR `meta_key` = %s )
812 GROUP BY `post_id`
813 )
814 ;",
815 self::$meta_prefix . 'meta-robots',
816 self::$meta_prefix . 'meta-robots-noindex',
817 self::$meta_prefix . 'meta-robots-nofollow',
818 );
819 $oldies = $wpdb->get_results( $query );
820
821 if ( is_array( $oldies ) && $oldies !== [] ) {
822 foreach ( $oldies as $old ) {
823 $old_values = explode( ',', $old->meta_value );
824 foreach ( $old_values as $value ) {
825 if ( $value === 'noindex' ) {
826 update_post_meta( $old->post_id, self::$meta_prefix . 'meta-robots-noindex', 1 );
827 }
828 elseif ( $value === 'nofollow' ) {
829 update_post_meta( $old->post_id, self::$meta_prefix . 'meta-robots-nofollow', 1 );
830 }
831 }
832 }
833 }
834 unset( $query, $oldies, $old, $old_values, $value );
835
836 // Delete old keys.
837 delete_post_meta_by_key( self::$meta_prefix . 'meta-robots' );
838
839 /*
840 * Remove all default values and (most) invalid option values.
841 * Invalid option values for the multiselect (meta-robots-adv) field will be dealt with seperately.
842 *
843 * {@internal Some of the defaults have changed in v1.5, but as the defaults will
844 * be removed and new defaults will now automatically be passed when no
845 * data found, this update is automatic (as long as we remove the old
846 * values which we do in the below routine).}}
847 *
848 * {@internal Unfortunately we can't use the normal delete_meta() with key/value combination
849 * as '' (empty string) values will be ignored and would result in all metas
850 * with that key being deleted, not just the empty fields.
851 * Still, the below implementation is largely based on the delete_meta() function.}}
852 */
853 $query = [];
854
855 foreach ( self::$meta_fields as $subset => $field_group ) {
856 foreach ( $field_group as $key => $field_def ) {
857 if ( ! isset( $field_def['default_value'] ) ) {
858 continue;
859 }
860
861 if ( isset( $field_def['options'] ) && is_array( $field_def['options'] ) && $field_def['options'] !== [] ) {
862 $valid = $field_def['options'];
863 // Remove the default value from the valid options.
864 unset( $valid[ $field_def['default_value'] ] );
865 $valid = array_keys( $valid );
866
867 $query[] = $wpdb->prepare(
868 "( meta_key = %s AND meta_value NOT IN ( '" . implode( "','", esc_sql( $valid ) ) . "' ) )",
869 self::$meta_prefix . $key,
870 );
871 unset( $valid );
872 }
873 elseif ( is_string( $field_def['default_value'] ) && $field_def['default_value'] !== '' ) {
874 $query[] = $wpdb->prepare(
875 '( meta_key = %s AND meta_value = %s )',
876 self::$meta_prefix . $key,
877 $field_def['default_value'],
878 );
879 }
880 else {
881 $query[] = $wpdb->prepare(
882 "( meta_key = %s AND meta_value = '' )",
883 self::$meta_prefix . $key,
884 );
885 }
886 }
887 }
888 unset( $subset, $field_group, $key, $field_def );
889
890 $query = "SELECT meta_id FROM {$wpdb->postmeta} WHERE " . implode( ' OR ', $query ) . ';';
891 $meta_ids = $wpdb->get_col( $query );
892
893 if ( is_array( $meta_ids ) && $meta_ids !== [] ) {
894 // WP native action.
895 do_action( 'delete_post_meta', $meta_ids, null, null, null );
896
897 $query = "DELETE FROM {$wpdb->postmeta} WHERE meta_id IN( " . implode( ',', $meta_ids ) . ' )';
898 $count = $wpdb->query( $query );
899
900 if ( $count ) {
901 foreach ( $meta_ids as $object_id ) {
902 wp_cache_delete( $object_id, 'post_meta' );
903 }
904
905 // WP native action.
906 do_action( 'deleted_post_meta', $meta_ids, null, null, null );
907 }
908 }
909 unset( $query, $meta_ids, $count, $object_id );
910
911 /*
912 * Deal with the multiselect (meta-robots-adv) field.
913 *
914 * Removes invalid option combinations, such as 'none,noarchive'.
915 *
916 * Default values have already been removed, so we should have a small result set and
917 * (hopefully) even smaller set of invalid results.
918 */
919 $query = $wpdb->prepare(
920 "SELECT meta_id, meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s",
921 self::$meta_prefix . 'meta-robots-adv',
922 );
923 $oldies = $wpdb->get_results( $query );
924
925 if ( is_array( $oldies ) && $oldies !== [] ) {
926 foreach ( $oldies as $old ) {
927 $clean = self::validate_meta_robots_adv( $old->meta_value );
928
929 if ( $clean !== $old->meta_value ) {
930 if ( $clean !== self::$meta_fields['advanced']['meta-robots-adv']['default_value'] ) {
931 update_metadata_by_mid( 'post', $old->meta_id, $clean );
932 }
933 else {
934 delete_metadata_by_mid( 'post', $old->meta_id );
935 }
936 }
937 }
938 }
939 unset( $query, $oldies, $old, $clean );
940
941 do_action( 'wpseo_meta_clean_up' );
942 }
943
944 /**
945 * Recursively merge a variable number of arrays, using the left array as base,
946 * giving priority to the right array.
947 *
948 * Difference with native array_merge_recursive():
949 * array_merge_recursive converts values with duplicate keys to arrays rather than
950 * overwriting the value in the first array with the duplicate value in the second array.
951 *
952 * array_merge_recursive_distinct does not change the data types of the values in the arrays.
953 * Matching keys' values in the second array overwrite those in the first array, as is the
954 * case with array_merge.
955 *
956 * Freely based on information found on http://www.php.net/manual/en/function.array-merge-recursive.php
957 *
958 * {@internal Should be moved to a general utility class.}}
959 *
960 * @return array
961 */
962 public static function array_merge_recursive_distinct() {
963
964 $arrays = func_get_args();
965 if ( count( $arrays ) < 2 ) {
966 if ( $arrays === [] ) {
967 return [];
968 }
969 else {
970 return $arrays[0];
971 }
972 }
973
974 $merged = array_shift( $arrays );
975
976 foreach ( $arrays as $array ) {
977 foreach ( $array as $key => $value ) {
978 if ( is_array( $value ) && ( isset( $merged[ $key ] ) && is_array( $merged[ $key ] ) ) ) {
979 $merged[ $key ] = self::array_merge_recursive_distinct( $merged[ $key ], $value );
980 }
981 else {
982 $merged[ $key ] = $value;
983 }
984 }
985 unset( $key, $value );
986 }
987
988 return $merged;
989 }
990
991 /**
992 * Counts the total of all the keywords being used for posts except the given one.
993 *
994 * @param string $keyword The keyword to be counted.
995 * @param int $post_id The id of the post to which the keyword belongs.
996 *
997 * @return array
998 */
999 public static function keyword_usage( $keyword, $post_id ) {
1000
1001 if ( empty( $keyword ) ) {
1002 return [];
1003 }
1004
1005 /**
1006 * The indexable repository.
1007 *
1008 * @var Indexable_Repository $repository
1009 */
1010 $repository = YoastSEO()->classes->get( Indexable_Repository::class );
1011
1012 $post_ids = $repository->query()
1013 ->select( 'object_id' )
1014 ->where( 'primary_focus_keyword', $keyword )
1015 ->where( 'object_type', 'post' )
1016 ->where_not_equal( 'object_id', $post_id )
1017 ->where_not_equal( 'post_status', 'trash' )
1018 ->limit( 2 ) // Limit to 2 results to save time and resources.
1019 ->find_array();
1020
1021 // Get object_id from each subarray in $post_ids.
1022 $post_ids = ( is_array( $post_ids ) ) ? array_column( $post_ids, 'object_id' ) : [];
1023
1024 /*
1025 * If Premium is installed, get the additional keywords as well.
1026 * We only check for the additional keywords if we've not already found two.
1027 * In that case there's no use for an additional query as we already know
1028 * that the keyword has been used multiple times before.
1029 */
1030 if ( count( $post_ids ) < 2 ) {
1031 /**
1032 * Allows enhancing the array of posts' that share their focus keywords with the post's focus keywords.
1033 *
1034 * @param array $post_ids The array of posts' ids that share their related keywords with the post.
1035 * @param string $keyword The keyword to search for.
1036 * @param int $post_id The id of the post the keyword is associated to.
1037 */
1038 $post_ids = apply_filters( 'wpseo_posts_for_focus_keyword', $post_ids, $keyword, $post_id );
1039 }
1040
1041 return $post_ids;
1042 }
1043
1044 /**
1045 * Returns the post types for the given post ids.
1046 *
1047 * @param array $post_ids The post ids to get the post types for.
1048 *
1049 * @return array The post types.
1050 */
1051 public static function post_types_for_ids( $post_ids ) {
1052 // Check if post ids is not empty.
1053 if ( ! empty( $post_ids ) ) {
1054 /**
1055 * The indexable repository.
1056 *
1057 * @var Indexable_Repository $repository
1058 */
1059 $repository = YoastSEO()->classes->get( Indexable_Repository::class );
1060
1061 // Get the post subtypes for the posts that share the keyword.
1062 $post_types = $repository->query()
1063 ->select( 'object_sub_type' )
1064 ->where_in( 'object_id', $post_ids )
1065 ->find_array();
1066
1067 // Get object_sub_type from each subarray in $post_ids.
1068 $post_types = array_column( $post_types, 'object_sub_type' );
1069 }
1070 else {
1071 $post_types = [];
1072 }
1073
1074 return $post_types;
1075 }
1076
1077 /**
1078 * Strips REST-exposed Yoast meta fields from the response for users without edit_post capability on the post.
1079 *
1080 * @param WP_REST_Response $response The REST response.
1081 * @param WP_Post $post The post object.
1082 *
1083 * @return WP_REST_Response The (possibly modified) response.
1084 */
1085 public static function hide_meta_from_unauthorized_rest_response( $response, $post ) {
1086 if ( current_user_can( 'edit_post', $post->ID ) ) {
1087 return $response;
1088 }
1089 $data = $response->get_data();
1090 foreach ( self::$meta_fields as $field_group ) {
1091 foreach ( $field_group as $key => $field_def ) {
1092 if ( ! empty( $field_def['show_in_rest'] ) ) {
1093 unset( $data['meta'][ self::$meta_prefix . $key ] );
1094 }
1095 }
1096 }
1097 $response->set_data( $data );
1098 return $response;
1099 }
1100
1101 /**
1102 * Filter the schema article types.
1103 *
1104 * @return void
1105 */
1106 public static function filter_schema_article_types() {
1107 /** This filter is documented in inc/options/class-wpseo-option-titles.php */
1108 self::$meta_fields['schema']['schema_article_type']['options'] = apply_filters( 'wpseo_schema_article_types', self::$meta_fields['schema']['schema_article_type']['options'] );
1109 }
1110 }
1111