PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / 18.0
Yoast SEO – Advanced SEO with real-time guidance and built-in AI v18.0
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 / options / class-wpseo-taxonomy-meta.php

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

558 lines 17.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\Options
6 */
7
8 /**
9 * Option: wpseo_taxonomy_meta.
10 */
11 class WPSEO_Taxonomy_Meta extends WPSEO_Option {
12
13 /**
14 * Option name.
15 *
16 * @var string
17 */
18 public $option_name = 'wpseo_taxonomy_meta';
19
20 /**
21 * Whether to include the option in the return for WPSEO_Options::get_all().
22 *
23 * @var bool
24 */
25 public $include_in_all = false;
26
27 /**
28 * Array of defaults for the option.
29 *
30 * Shouldn't be requested directly, use $this->get_defaults();
31 *
32 * {@internal Important: in contrast to most defaults, the below array format is
33 * very bare. The real option is in the format [taxonomy_name][term_id][...]
34 * where [...] is any of the $defaults_per_term options shown below.
35 * This is of course taken into account in the below methods.}}
36 *
37 * @var array
38 */
39 protected $defaults = [];
40
41 /**
42 * Option name - same as $option_name property, but now also available to static methods.
43 *
44 * @var string
45 */
46 public static $name;
47
48 /**
49 * Array of defaults for individual taxonomy meta entries.
50 *
51 * @var array
52 */
53 public static $defaults_per_term = [
54 'wpseo_title' => '',
55 'wpseo_desc' => '',
56 'wpseo_canonical' => '',
57 'wpseo_bctitle' => '',
58 'wpseo_noindex' => 'default',
59 'wpseo_focuskw' => '',
60 'wpseo_linkdex' => '',
61 'wpseo_content_score' => '',
62 'wpseo_focuskeywords' => '[]',
63 'wpseo_keywordsynonyms' => '[]',
64 'wpseo_is_cornerstone' => '0',
65
66 // Social fields.
67 'wpseo_opengraph-title' => '',
68 'wpseo_opengraph-description' => '',
69 'wpseo_opengraph-image' => '',
70 'wpseo_opengraph-image-id' => '',
71 'wpseo_twitter-title' => '',
72 'wpseo_twitter-description' => '',
73 'wpseo_twitter-image' => '',
74 'wpseo_twitter-image-id' => '',
75 ];
76
77 /**
78 * Available index options.
79 *
80 * Used for form generation and input validation.
81 *
82 * {@internal Labels (translation) added on admin_init via WPSEO_Taxonomy::translate_meta_options().}}
83 *
84 * @var array
85 */
86 public static $no_index_options = [
87 'default' => '',
88 'index' => '',
89 'noindex' => '',
90 ];
91
92 /**
93 * Add the actions and filters for the option.
94 *
95 * @todo [JRF => testers] Check if the extra actions below would run into problems if an option
96 * is updated early on and if so, change the call to schedule these for a later action on add/update
97 * instead of running them straight away.
98 */
99 protected function __construct() {
100 parent::__construct();
101
102 self::$name = $this->option_name;
103 }
104
105 /**
106 * Get the singleton instance of this class.
107 *
108 * @return object
109 */
110 public static function get_instance() {
111 if ( ! ( self::$instance instanceof self ) ) {
112 self::$instance = new self();
113 self::$name = self::$instance->option_name;
114 }
115
116 return self::$instance;
117 }
118
119 /**
120 * Add extra default options received from a filter.
121 */
122 public function enrich_defaults() {
123 $extra_defaults_per_term = apply_filters( 'wpseo_add_extra_taxmeta_term_defaults', [] );
124 if ( is_array( $extra_defaults_per_term ) ) {
125 self::$defaults_per_term = array_merge( $extra_defaults_per_term, self::$defaults_per_term );
126 }
127 }
128
129 /**
130 * Validate the option.
131 *
132 * @param array $dirty New value for the option.
133 * @param array $clean Clean value for the option, normally the defaults.
134 * @param array $old Old value of the option.
135 *
136 * @return array Validated clean value for the option to be saved to the database.
137 */
138 protected function validate_option( $dirty, $clean, $old ) {
139 /*
140 * Prevent complete validation (which can be expensive when there are lots of terms)
141 * if only one item has changed and has already been validated.
142 */
143 if ( isset( $dirty['wpseo_already_validated'] ) && $dirty['wpseo_already_validated'] === true ) {
144 unset( $dirty['wpseo_already_validated'] );
145
146 return $dirty;
147 }
148
149 foreach ( $dirty as $taxonomy => $terms ) {
150 /* Don't validate taxonomy - may not be registered yet and we don't want to remove valid ones. */
151 if ( is_array( $terms ) && $terms !== [] ) {
152 foreach ( $terms as $term_id => $meta_data ) {
153 /* Only validate term if the taxonomy exists. */
154 if ( taxonomy_exists( $taxonomy ) && get_term_by( 'id', $term_id, $taxonomy ) === false ) {
155 /* Is this term id a special case ? */
156 if ( has_filter( 'wpseo_tax_meta_special_term_id_validation_' . $term_id ) !== false ) {
157 $clean[ $taxonomy ][ $term_id ] = apply_filters( 'wpseo_tax_meta_special_term_id_validation_' . $term_id, $meta_data, $taxonomy, $term_id );
158 }
159 continue;
160 }
161
162 if ( is_array( $meta_data ) && $meta_data !== [] ) {
163 /* Validate meta data. */
164 $old_meta = self::get_term_meta( $term_id, $taxonomy );
165 $meta_data = self::validate_term_meta_data( $meta_data, $old_meta );
166 if ( $meta_data !== [] ) {
167 $clean[ $taxonomy ][ $term_id ] = $meta_data;
168 }
169 }
170
171 // Deal with special cases (for when taxonomy doesn't exist yet).
172 if ( ! isset( $clean[ $taxonomy ][ $term_id ] ) && has_filter( 'wpseo_tax_meta_special_term_id_validation_' . $term_id ) !== false ) {
173 $clean[ $taxonomy ][ $term_id ] = apply_filters( 'wpseo_tax_meta_special_term_id_validation_' . $term_id, $meta_data, $taxonomy, $term_id );
174 }
175 }
176 }
177 }
178
179 return $clean;
180 }
181
182 /**
183 * Validate the meta data for one individual term and removes default values (no need to save those).
184 *
185 * @param array $meta_data New values.
186 * @param array $old_meta The original values.
187 *
188 * @return array Validated and filtered value.
189 */
190 public static function validate_term_meta_data( $meta_data, $old_meta ) {
191
192 $clean = self::$defaults_per_term;
193 $meta_data = array_map( [ 'WPSEO_Utils', 'trim_recursive' ], $meta_data );
194
195 if ( ! is_array( $meta_data ) || $meta_data === [] ) {
196 return $clean;
197 }
198
199 foreach ( $clean as $key => $value ) {
200 switch ( $key ) {
201
202 case 'wpseo_noindex':
203 if ( isset( $meta_data[ $key ] ) ) {
204 if ( isset( self::$no_index_options[ $meta_data[ $key ] ] ) ) {
205 $clean[ $key ] = $meta_data[ $key ];
206 }
207 }
208 elseif ( isset( $old_meta[ $key ] ) ) {
209 // Retain old value if field currently not in use.
210 $clean[ $key ] = $old_meta[ $key ];
211 }
212 break;
213
214 case 'wpseo_canonical':
215 if ( isset( $meta_data[ $key ] ) && $meta_data[ $key ] !== '' ) {
216 $url = WPSEO_Utils::sanitize_url( $meta_data[ $key ] );
217 if ( $url !== '' ) {
218 $clean[ $key ] = $url;
219 }
220 unset( $url );
221 }
222 break;
223
224 case 'wpseo_bctitle':
225 if ( isset( $meta_data[ $key ] ) ) {
226 $clean[ $key ] = WPSEO_Utils::sanitize_text_field( $meta_data[ $key ] );
227 }
228 elseif ( isset( $old_meta[ $key ] ) ) {
229 // Retain old value if field currently not in use.
230 $clean[ $key ] = $old_meta[ $key ];
231 }
232 break;
233
234 case 'wpseo_keywordsynonyms':
235 if ( isset( $meta_data[ $key ] ) && is_string( $meta_data[ $key ] ) ) {
236 // The data is stringified JSON. Use `json_decode` and `json_encode` around the sanitation.
237 $input = json_decode( $meta_data[ $key ], true );
238 $sanitized = array_map( [ 'WPSEO_Utils', 'sanitize_text_field' ], $input );
239 $clean[ $key ] = WPSEO_Utils::format_json_encode( $sanitized );
240 }
241 elseif ( isset( $old_meta[ $key ] ) ) {
242 // Retain old value if field currently not in use.
243 $clean[ $key ] = $old_meta[ $key ];
244 }
245 break;
246
247 case 'wpseo_focuskeywords':
248 if ( isset( $meta_data[ $key ] ) && is_string( $meta_data[ $key ] ) ) {
249 // The data is stringified JSON. Use `json_decode` and `json_encode` around the sanitation.
250 $input = json_decode( $meta_data[ $key ], true );
251
252 // This data has two known keys: `keyword` and `score`.
253 $sanitized = [];
254 foreach ( $input as $entry ) {
255 $sanitized[] = [
256 'keyword' => WPSEO_Utils::sanitize_text_field( $entry['keyword'] ),
257 'score' => WPSEO_Utils::sanitize_text_field( $entry['score'] ),
258 ];
259 }
260
261 $clean[ $key ] = WPSEO_Utils::format_json_encode( $sanitized );
262 }
263 elseif ( isset( $old_meta[ $key ] ) ) {
264 // Retain old value if field currently not in use.
265 $clean[ $key ] = $old_meta[ $key ];
266 }
267 break;
268
269 case 'wpseo_focuskw':
270 case 'wpseo_title':
271 case 'wpseo_desc':
272 case 'wpseo_linkdex':
273 default:
274 if ( isset( $meta_data[ $key ] ) && is_string( $meta_data[ $key ] ) ) {
275 $clean[ $key ] = WPSEO_Utils::sanitize_text_field( $meta_data[ $key ] );
276 }
277
278 if ( $key === 'wpseo_focuskw' ) {
279 $search = [
280 '&lt;',
281 '&gt;',
282 '&#96',
283 '<',
284 '>',
285 '`',
286 ];
287
288 $clean[ $key ] = str_replace( $search, '', $clean[ $key ] );
289 }
290 break;
291 }
292
293 $clean[ $key ] = apply_filters( 'wpseo_sanitize_tax_meta_' . $key, $clean[ $key ], ( isset( $meta_data[ $key ] ) ? $meta_data[ $key ] : null ), ( isset( $old_meta[ $key ] ) ? $old_meta[ $key ] : null ) );
294 }
295
296 // Only save the non-default values.
297 return array_diff_assoc( $clean, self::$defaults_per_term );
298 }
299
300 /**
301 * Clean a given option value.
302 * - Convert old option values to new
303 * - Fixes strings which were escaped (should have been sanitized - escaping is for output)
304 *
305 * @param array $option_value Old (not merged with defaults or filtered) option value to
306 * clean according to the rules for this option.
307 * @param string|null $current_version Optional. Version from which to upgrade, if not set,
308 * version specific upgrades will be disregarded.
309 * @param array|null $all_old_option_values Optional. Only used when importing old options to have
310 * access to the real old values, in contrast to the saved ones.
311 *
312 * @return array Cleaned option.
313 */
314 protected function clean_option( $option_value, $current_version = null, $all_old_option_values = null ) {
315
316 /* Clean up old values and remove empty arrays. */
317 if ( is_array( $option_value ) && $option_value !== [] ) {
318
319 foreach ( $option_value as $taxonomy => $terms ) {
320
321 if ( is_array( $terms ) && $terms !== [] ) {
322
323 foreach ( $terms as $term_id => $meta_data ) {
324 if ( ! is_array( $meta_data ) || $meta_data === [] ) {
325 // Remove empty term arrays.
326 unset( $option_value[ $taxonomy ][ $term_id ] );
327 }
328 else {
329 foreach ( $meta_data as $key => $value ) {
330
331 switch ( $key ) {
332 case 'noindex':
333 if ( $value === 'on' ) {
334 // Convert 'on' to 'noindex'.
335 $option_value[ $taxonomy ][ $term_id ][ $key ] = 'noindex';
336 }
337 break;
338
339 case 'canonical':
340 case 'wpseo_bctitle':
341 case 'wpseo_title':
342 case 'wpseo_desc':
343 case 'wpseo_linkdex':
344 // @todo [JRF => whomever] Needs checking, I don't have example data [JRF].
345 if ( $value !== '' ) {
346 // Fix incorrectly saved (encoded) canonical urls and texts.
347 $option_value[ $taxonomy ][ $term_id ][ $key ] = wp_specialchars_decode( stripslashes( $value ), ENT_QUOTES );
348 }
349 break;
350
351 default:
352 // @todo [JRF => whomever] Needs checking, I don't have example data [JRF].
353 if ( $value !== '' ) {
354 // Fix incorrectly saved (escaped) text strings.
355 $option_value[ $taxonomy ][ $term_id ][ $key ] = wp_specialchars_decode( $value, ENT_QUOTES );
356 }
357 break;
358 }
359 }
360 }
361 }
362 }
363 else {
364 // Remove empty taxonomy arrays.
365 unset( $option_value[ $taxonomy ] );
366 }
367 }
368 }
369
370 return $option_value;
371 }
372
373 /**
374 * Retrieve a taxonomy term's meta value(s).
375 *
376 * @param mixed $term Term to get the meta value for
377 * either (string) term name, (int) term id or (object) term.
378 * @param string $taxonomy Name of the taxonomy to which the term is attached.
379 * @param string|null $meta Optional. Meta value to get (without prefix).
380 *
381 * @return mixed Value for the $meta if one is given, might be the default.
382 * If no meta is given, an array of all the meta data for the term.
383 * False if the term does not exist or the $meta provided is invalid.
384 */
385 public static function get_term_meta( $term, $taxonomy, $meta = null ) {
386 /* Figure out the term id. */
387 if ( is_int( $term ) ) {
388 $term = get_term_by( 'id', $term, $taxonomy );
389 }
390 elseif ( is_string( $term ) ) {
391 $term = get_term_by( 'slug', $term, $taxonomy );
392 }
393
394 if ( is_object( $term ) && isset( $term->term_id ) ) {
395 $term_id = $term->term_id;
396 }
397 else {
398 return false;
399 }
400
401 $tax_meta = self::get_term_tax_meta( $term_id, $taxonomy );
402
403 /*
404 * Either return the complete array or a single value from it or false if the value does not exist
405 * (shouldn't happen after merge with defaults, indicates typo in request).
406 */
407 if ( ! isset( $meta ) ) {
408 return $tax_meta;
409 }
410
411
412 if ( isset( $tax_meta[ 'wpseo_' . $meta ] ) ) {
413 return $tax_meta[ 'wpseo_' . $meta ];
414 }
415
416 return false;
417 }
418
419 /**
420 * Get the current queried object and return the meta value.
421 *
422 * @param string $meta The meta field that is needed.
423 *
424 * @return mixed
425 */
426 public static function get_meta_without_term( $meta ) {
427 $term = $GLOBALS['wp_query']->get_queried_object();
428 if ( ! $term || empty( $term->taxonomy ) ) {
429 return false;
430 }
431
432 return self::get_term_meta( $term, $term->taxonomy, $meta );
433 }
434
435 /**
436 * Saving the values for the given term_id.
437 *
438 * @param int $term_id ID of the term to save data for.
439 * @param string $taxonomy The taxonomy the term belongs to.
440 * @param array $meta_values The values that will be saved.
441 */
442 public static function set_values( $term_id, $taxonomy, array $meta_values ) {
443 /* Validate the post values */
444 $old = self::get_term_meta( $term_id, $taxonomy );
445 $clean = self::validate_term_meta_data( $meta_values, $old );
446
447 self::save_clean_values( $term_id, $taxonomy, $clean );
448 }
449
450 /**
451 * Setting a single value to the term meta.
452 *
453 * @param int $term_id ID of the term to save data for.
454 * @param string $taxonomy The taxonomy the term belongs to.
455 * @param string $meta_key The target meta key to store the value in.
456 * @param string $meta_value The value of the target meta key.
457 */
458 public static function set_value( $term_id, $taxonomy, $meta_key, $meta_value ) {
459
460 if ( substr( strtolower( $meta_key ), 0, 6 ) !== 'wpseo_' ) {
461 $meta_key = 'wpseo_' . $meta_key;
462 }
463
464 self::set_values( $term_id, $taxonomy, [ $meta_key => $meta_value ] );
465 }
466
467 /**
468 * Find the keyword usages in the metas for the taxonomies/terms.
469 *
470 * @param string $keyword The keyword to look for.
471 * @param string $current_term_id The current term id.
472 * @param string $current_taxonomy The current taxonomy name.
473 *
474 * @return array
475 */
476 public static function get_keyword_usage( $keyword, $current_term_id, $current_taxonomy ) {
477 $tax_meta = self::get_tax_meta();
478
479
480 $found = [];
481 // @todo Check for terms of all taxonomies, not only the current taxonomy.
482 foreach ( $tax_meta as $taxonomy_name => $terms ) {
483 foreach ( $terms as $term_id => $meta_values ) {
484 $is_current = ( $current_taxonomy === $taxonomy_name && (string) $current_term_id === (string) $term_id );
485 if ( ! $is_current && ! empty( $meta_values['wpseo_focuskw'] ) && $meta_values['wpseo_focuskw'] === $keyword ) {
486 $found[] = $term_id;
487 }
488 }
489 }
490
491 return [ $keyword => $found ];
492 }
493
494 /**
495 * Saving the values for the given term_id.
496 *
497 * @param int $term_id ID of the term to save data for.
498 * @param string $taxonomy The taxonomy the term belongs to.
499 * @param array $clean Array with clean values.
500 */
501 private static function save_clean_values( $term_id, $taxonomy, array $clean ) {
502 $tax_meta = self::get_tax_meta();
503
504 /* Add/remove the result to/from the original option value. */
505 if ( $clean !== [] ) {
506 $tax_meta[ $taxonomy ][ $term_id ] = $clean;
507 }
508 else {
509 unset( $tax_meta[ $taxonomy ][ $term_id ] );
510 if ( isset( $tax_meta[ $taxonomy ] ) && $tax_meta[ $taxonomy ] === [] ) {
511 unset( $tax_meta[ $taxonomy ] );
512 }
513 }
514
515 // Prevent complete array validation.
516 $tax_meta['wpseo_already_validated'] = true;
517
518 self::save_tax_meta( $tax_meta );
519 }
520
521 /**
522 * Getting the meta from the options.
523 *
524 * @return void|array
525 */
526 private static function get_tax_meta() {
527 return get_option( self::$name );
528 }
529
530 /**
531 * Saving the tax meta values to the database.
532 *
533 * @param array $tax_meta Array with the meta values for taxonomy.
534 */
535 private static function save_tax_meta( $tax_meta ) {
536 update_option( self::$name, $tax_meta );
537 }
538
539 /**
540 * Getting the taxonomy meta for the given term_id and taxonomy.
541 *
542 * @param int $term_id The id of the term.
543 * @param string $taxonomy Name of the taxonomy to which the term is attached.
544 *
545 * @return array
546 */
547 private static function get_term_tax_meta( $term_id, $taxonomy ) {
548 $tax_meta = self::get_tax_meta();
549
550 /* If we have data for the term, merge with defaults for complete array, otherwise set defaults. */
551 if ( isset( $tax_meta[ $taxonomy ][ $term_id ] ) ) {
552 return array_merge( self::$defaults_per_term, $tax_meta[ $taxonomy ][ $term_id ] );
553 }
554
555 return self::$defaults_per_term;
556 }
557 }
558