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 / inc / class-wpseo-meta.php

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

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