PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 27.6
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v27.6
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 27.6, at inc/class-wpseo-meta.php

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