PluginProbe
Yoast SEO – Advanced SEO with real-time guidance and built-in AI / trunk
Yoast SEO – Advanced SEO with real-time guidance and built-in AI vtrunk
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-utils.php

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

1,113 lines 29.0 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.8.0
7 */
8
9 use Yoast\WP\SEO\Integrations\Feature_Flag_Integration;
10
11 /**
12 * Group of utility methods for use by WPSEO.
13 * All methods are static, this is just a sort of namespacing class wrapper.
14 */
15 class WPSEO_Utils {
16
17 /**
18 * Whether the PHP filter extension is enabled.
19 *
20 * @since 1.8.0
21 *
22 * @var bool
23 */
24 public static $has_filters;
25
26 /**
27 * Check whether file editing is allowed for the .htaccess and robots.txt files.
28 *
29 * {@internal current_user_can() checks internally whether a user is on wp-ms and adjusts accordingly.}}
30 *
31 * @since 1.8.0
32 *
33 * @return bool
34 */
35 public static function allow_system_file_edit() {
36 $allowed = true;
37
38 if ( current_user_can( 'edit_files' ) === false ) {
39 $allowed = false;
40 }
41
42 /**
43 * Filter: 'wpseo_allow_system_file_edit' - Allow developers to change whether the editing of
44 * .htaccess and robots.txt is allowed.
45 *
46 * @param bool $allowed Whether file editing is allowed.
47 */
48 return apply_filters( 'wpseo_allow_system_file_edit', $allowed );
49 }
50
51 /**
52 * Check if the web server is running on Apache or compatible (LiteSpeed).
53 *
54 * @since 1.8.0
55 *
56 * @return bool
57 */
58 public static function is_apache() {
59 if ( ! isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
60 return false;
61 }
62
63 $software = sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) );
64
65 return stripos( $software, 'apache' ) !== false || stripos( $software, 'litespeed' ) !== false;
66 }
67
68 /**
69 * Check if the web server is running on Nginx.
70 *
71 * @since 1.8.0
72 *
73 * @return bool
74 */
75 public static function is_nginx() {
76 if ( ! isset( $_SERVER['SERVER_SOFTWARE'] ) ) {
77 return false;
78 }
79
80 $software = sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) );
81
82 return stripos( $software, 'nginx' ) !== false;
83 }
84
85 /**
86 * Check whether a url is relative.
87 *
88 * @since 1.8.0
89 *
90 * @param string $url URL string to check.
91 *
92 * @return bool
93 */
94 public static function is_url_relative( $url ) {
95 return YoastSEO()->helpers->url->is_relative( $url );
96 }
97
98 /**
99 * Recursively trim whitespace round a string value or of string values within an array.
100 * Only trims strings to avoid typecasting a variable (to string).
101 *
102 * @since 1.8.0
103 *
104 * @param mixed $value Value to trim or array of values to trim.
105 *
106 * @return mixed Trimmed value or array of trimmed values.
107 */
108 public static function trim_recursive( $value ) {
109 if ( is_string( $value ) ) {
110 $value = trim( $value );
111 }
112 elseif ( is_array( $value ) ) {
113 $value = array_map( [ self::class, 'trim_recursive' ], $value );
114 }
115
116 return $value;
117 }
118
119 /**
120 * Emulate the WP native sanitize_text_field function in a %%variable%% safe way.
121 *
122 * Sanitize a string from user input or from the db.
123 *
124 * - Check for invalid UTF-8;
125 * - Convert single < characters to entity;
126 * - Strip all tags;
127 * - Remove line breaks, tabs and extra white space;
128 * - Strip octets - BUT DO NOT REMOVE (part of) VARIABLES WHICH WILL BE REPLACED.
129 *
130 * @link https://core.trac.wordpress.org/browser/trunk/src/wp-includes/formatting.php for the original.
131 *
132 * @since 1.8.0
133 *
134 * @param string $value String value to sanitize.
135 *
136 * @return string
137 */
138 public static function sanitize_text_field( $value ) {
139 $filtered = wp_check_invalid_utf8( $value );
140
141 if ( strpos( $filtered, '<' ) !== false ) {
142 $filtered = wp_pre_kses_less_than( $filtered );
143 // This will strip extra whitespace for us.
144 $filtered = wp_strip_all_tags( $filtered, true );
145 }
146 else {
147 $filtered = trim( preg_replace( '`[\r\n\t ]+`', ' ', $filtered ) );
148 }
149
150 $found = false;
151 while ( preg_match( '`[^%](%[a-f0-9]{2})`i', $filtered, $match ) ) {
152 $filtered = str_replace( $match[1], '', $filtered );
153 $found = true;
154 }
155 unset( $match );
156
157 if ( $found ) {
158 // Strip out the whitespace that may now exist after removing the octets.
159 $filtered = trim( preg_replace( '` +`', ' ', $filtered ) );
160 }
161
162 /**
163 * Filter a sanitized text field string.
164 *
165 * @since WP 2.9.0
166 *
167 * @param string $filtered The sanitized string.
168 * @param string $str The string prior to being sanitized.
169 */
170 return apply_filters( 'sanitize_text_field', $filtered, $value ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals -- Using WP native filter.
171 }
172
173 /**
174 * Sanitize a url for saving to the database.
175 * Not to be confused with the old native WP function.
176 *
177 * @since 1.8.0
178 *
179 * @param string $value String URL value to sanitize.
180 * @param array $allowed_protocols Optional set of allowed protocols.
181 *
182 * @return string
183 */
184 public static function sanitize_url( $value, $allowed_protocols = [ 'http', 'https' ] ) {
185
186 // Percent-encode non-ASCII bytes in the path/query/fragment before parsing, so wp_parse_url()
187 // does not corrupt multibyte UTF-8 characters. The authority (userinfo + host) is left untouched
188 // to avoid double-encoding it during the sanitization below.
189 if ( preg_match( '/[\x80-\xff]/', $value ) === 1 ) {
190 preg_match( '`^((?:[a-z][a-z0-9+.\-]*:)?//[^/?#]*)?(.*)$`is', $value, $split );
191 $value = $split[1] . preg_replace_callback(
192 '/[\x80-\xff]/',
193 static function ( $bytes ) {
194 return rawurlencode( $bytes[0] );
195 },
196 $split[2],
197 );
198 }
199
200 $url = '';
201 $parts = wp_parse_url( $value );
202
203 if ( isset( $parts['scheme'], $parts['host'] ) ) {
204 $url = $parts['scheme'] . '://';
205
206 if ( isset( $parts['user'] ) ) {
207 $url .= rawurlencode( $parts['user'] );
208 $url .= isset( $parts['pass'] ) ? ':' . rawurlencode( $parts['pass'] ) : '';
209 $url .= '@';
210 }
211
212 $parts['host'] = preg_replace(
213 '`[^a-z0-9-.:\[\]\\x80-\\xff]`',
214 '',
215 strtolower( $parts['host'] ),
216 );
217
218 $url .= $parts['host'] . ( isset( $parts['port'] ) ? ':' . (int) $parts['port'] : '' );
219 }
220
221 if ( isset( $parts['path'] ) && strpos( $parts['path'], '/' ) === 0 ) {
222 $path = explode( '/', wp_strip_all_tags( $parts['path'] ) );
223 $path = self::sanitize_encoded_text_field( $path );
224 $url .= str_replace( '%40', '@', implode( '/', $path ) );
225 }
226
227 if ( ! $url ) {
228 return '';
229 }
230
231 if ( isset( $parts['query'] ) ) {
232 wp_parse_str( $parts['query'], $parsed_query );
233
234 $parsed_query = array_combine(
235 self::sanitize_encoded_text_field( array_keys( $parsed_query ) ),
236 self::sanitize_encoded_text_field( array_values( $parsed_query ) ),
237 );
238
239 $url = add_query_arg( $parsed_query, $url );
240 }
241
242 if ( isset( $parts['fragment'] ) ) {
243 $url .= '#' . self::sanitize_encoded_text_field( $parts['fragment'] );
244 }
245
246 if ( strpos( $url, '%' ) !== false ) {
247 $url = preg_replace_callback(
248 '`%[a-fA-F0-9]{2}`',
249 static function ( $octects ) {
250 return strtolower( $octects[0] );
251 },
252 $url,
253 );
254 }
255
256 return esc_url_raw( $url, $allowed_protocols );
257 }
258
259 /**
260 * Decode, sanitize and encode the array of strings or the string.
261 *
262 * @since 13.3
263 *
264 * @param array|string $value The value to sanitize and encode.
265 *
266 * @return array|string The sanitized value.
267 */
268 public static function sanitize_encoded_text_field( $value ) {
269 if ( is_array( $value ) ) {
270 return array_map( [ self::class, 'sanitize_encoded_text_field' ], $value );
271 }
272
273 return rawurlencode( sanitize_text_field( rawurldecode( $value ) ) );
274 }
275
276 /**
277 * Validate a value as boolean.
278 *
279 * @since 1.8.0
280 *
281 * @param mixed $value Value to validate.
282 *
283 * @return bool
284 */
285 public static function validate_bool( $value ) {
286 if ( ! isset( self::$has_filters ) ) {
287 self::$has_filters = extension_loaded( 'filter' );
288 }
289
290 if ( self::$has_filters ) {
291 return filter_var( $value, FILTER_VALIDATE_BOOLEAN );
292 }
293 else {
294 return self::emulate_filter_bool( $value );
295 }
296 }
297
298 /**
299 * Cast a value to bool.
300 *
301 * @since 1.8.0
302 *
303 * @param mixed $value Value to cast.
304 *
305 * @return bool
306 */
307 public static function emulate_filter_bool( $value ) {
308 $true = [
309 '1',
310 'true',
311 'True',
312 'TRUE',
313 'y',
314 'Y',
315 'yes',
316 'Yes',
317 'YES',
318 'on',
319 'On',
320 'ON',
321 ];
322 $false = [
323 '0',
324 'false',
325 'False',
326 'FALSE',
327 'n',
328 'N',
329 'no',
330 'No',
331 'NO',
332 'off',
333 'Off',
334 'OFF',
335 ];
336
337 if ( is_bool( $value ) ) {
338 return $value;
339 }
340 elseif ( is_int( $value ) && ( $value === 0 || $value === 1 ) ) {
341 return (bool) $value;
342 }
343 elseif ( ( is_float( $value ) && ! is_nan( $value ) ) && ( $value === (float) 0 || $value === (float) 1 ) ) {
344 return (bool) $value;
345 }
346 elseif ( is_string( $value ) ) {
347 $value = trim( $value );
348 if ( in_array( $value, $true, true ) ) {
349 return true;
350 }
351 elseif ( in_array( $value, $false, true ) ) {
352 return false;
353 }
354 else {
355 return false;
356 }
357 }
358
359 return false;
360 }
361
362 /**
363 * Validate a value as integer.
364 *
365 * @since 1.8.0
366 *
367 * @param mixed $value Value to validate.
368 *
369 * @return int|bool Int or false in case of failure to convert to int.
370 */
371 public static function validate_int( $value ) {
372 if ( ! isset( self::$has_filters ) ) {
373 self::$has_filters = extension_loaded( 'filter' );
374 }
375
376 if ( self::$has_filters ) {
377 return filter_var( $value, FILTER_VALIDATE_INT );
378 }
379 else {
380 return self::emulate_filter_int( $value );
381 }
382 }
383
384 /**
385 * Cast a value to integer.
386 *
387 * @since 1.8.0
388 *
389 * @param mixed $value Value to cast.
390 *
391 * @return int|bool
392 */
393 public static function emulate_filter_int( $value ) {
394 if ( is_int( $value ) ) {
395 return $value;
396 }
397 elseif ( is_float( $value ) ) {
398 // phpcs:ignore Universal.Operators.StrictComparisons -- Purposeful loose comparison.
399 if ( (int) $value == $value && ! is_nan( $value ) ) {
400 return (int) $value;
401 }
402 else {
403 return false;
404 }
405 }
406 elseif ( is_string( $value ) ) {
407 $value = trim( $value );
408 if ( $value === '' ) {
409 return false;
410 }
411 elseif ( ctype_digit( $value ) ) {
412 return (int) $value;
413 }
414 elseif ( strpos( $value, '-' ) === 0 && ctype_digit( substr( $value, 1 ) ) ) {
415 return (int) $value;
416 }
417 else {
418 return false;
419 }
420 }
421
422 return false;
423 }
424
425 /**
426 * Clears the WP or W3TC cache depending on which is used.
427 *
428 * @since 1.8.0
429 *
430 * @return void
431 */
432 public static function clear_cache() {
433 if ( function_exists( 'w3tc_flush_posts' ) ) {
434 w3tc_flush_posts();
435 }
436 elseif ( function_exists( 'wp_cache_clear_cache' ) ) {
437 wp_cache_clear_cache();
438 }
439 }
440
441 /**
442 * Clear rewrite rules.
443 *
444 * @since 1.8.0
445 *
446 * @return void
447 */
448 public static function clear_rewrites() {
449 update_option( 'rewrite_rules', '' );
450 }
451
452 /**
453 * Do simple reliable math calculations without the risk of wrong results.
454 *
455 * In the rare case that the bcmath extension would not be loaded, it will return the normal calculation results.
456 *
457 * @link http://floating-point-gui.de/
458 * @link http://php.net/language.types.float.php See the big red warning.
459 *
460 * @since 1.5.0
461 * @since 1.8.0 Moved from stand-alone function to this class.
462 *
463 * @param mixed $number1 Scalar (string/int/float/bool).
464 * @param string $action Calculation action to execute. Valid input:
465 * '+' or 'add' or 'addition',
466 * '-' or 'sub' or 'subtract',
467 * '*' or 'mul' or 'multiply',
468 * '/' or 'div' or 'divide',
469 * '%' or 'mod' or 'modulus'
470 * '=' or 'comp' or 'compare'.
471 * @param mixed $number2 Scalar (string/int/float/bool).
472 * @param bool $round Whether or not to round the result. Defaults to false.
473 * Will be disregarded for a compare operation.
474 * @param int $decimals Decimals for rounding operation. Defaults to 0.
475 * @param int $precision Calculation precision. Defaults to 10.
476 *
477 * @return mixed Calculation Result or false if either or the numbers isn't scalar or
478 * an invalid operation was passed.
479 * - For compare the result will always be an integer.
480 * - For all other operations, the result will either be an integer (preferred)
481 * or a float.
482 */
483 public static function calc( $number1, $action, $number2, $round = false, $decimals = 0, $precision = 10 ) {
484 static $bc;
485
486 if ( ! is_scalar( $number1 ) || ! is_scalar( $number2 ) ) {
487 return false;
488 }
489
490 if ( ! isset( $bc ) ) {
491 $bc = extension_loaded( 'bcmath' );
492 }
493
494 if ( $bc ) {
495 $number1 = number_format( $number1, 10, '.', '' );
496 $number2 = number_format( $number2, 10, '.', '' );
497 }
498
499 $result = null;
500 $compare = false;
501
502 switch ( $action ) {
503 case '+':
504 case 'add':
505 case 'addition':
506 $result = ( $bc ) ? bcadd( $number1, $number2, $precision ) /* string */ : ( $number1 + $number2 );
507 break;
508
509 case '-':
510 case 'sub':
511 case 'subtract':
512 $result = ( $bc ) ? bcsub( $number1, $number2, $precision ) /* string */ : ( $number1 - $number2 );
513 break;
514
515 case '*':
516 case 'mul':
517 case 'multiply':
518 $result = ( $bc ) ? bcmul( $number1, $number2, $precision ) /* string */ : ( $number1 * $number2 );
519 break;
520
521 case '/':
522 case 'div':
523 case 'divide':
524 if ( $bc ) {
525 $result = bcdiv( $number1, $number2, $precision ); // String, or NULL if right_operand is 0.
526 }
527 elseif ( $number2 != 0 ) { // phpcs:ignore Universal.Operators.StrictComparisons -- Purposeful loose comparison.
528 $result = ( $number1 / $number2 );
529 }
530
531 if ( ! isset( $result ) ) {
532 $result = 0;
533 }
534 break;
535
536 case '%':
537 case 'mod':
538 case 'modulus':
539 if ( $bc ) {
540 $result = bcmod( $number1, $number2 ); // String, or NULL if modulus is 0.
541 }
542 elseif ( $number2 != 0 ) { // phpcs:ignore Universal.Operators.StrictComparisons -- Purposeful loose comparison.
543 $result = ( $number1 % $number2 );
544 }
545
546 if ( ! isset( $result ) ) {
547 $result = 0;
548 }
549 break;
550
551 case '=':
552 case 'comp':
553 case 'compare':
554 $compare = true;
555 if ( $bc ) {
556 $result = bccomp( $number1, $number2, $precision ); // Returns int 0, 1 or -1.
557 }
558 else {
559 // phpcs:ignore Universal.Operators.StrictComparisons -- Purposeful loose comparison.
560 $result = ( $number1 == $number2 ) ? 0 : ( ( $number1 > $number2 ) ? 1 : -1 );
561 }
562 break;
563 }
564
565 if ( isset( $result ) ) {
566 if ( $compare === false ) {
567 if ( $round === true ) {
568 $result = round( (float) $result, $decimals );
569 if ( $decimals === 0 ) {
570 $result = (int) $result;
571 }
572 }
573 else {
574 // phpcs:ignore Universal.Operators.StrictComparisons -- Purposeful loose comparison.
575 $result = ( intval( $result ) == $result ) ? (int) $result : (float) $result;
576 }
577 }
578
579 return $result;
580 }
581
582 return false;
583 }
584
585 /**
586 * Trim whitespace and NBSP (Non-breaking space) from string.
587 *
588 * @since 2.0.0
589 *
590 * @param string $text String input to trim.
591 *
592 * @return string
593 */
594 public static function trim_nbsp_from_string( $text ) {
595 $find = [ '&nbsp;', chr( 0xC2 ) . chr( 0xA0 ) ];
596 $text = str_replace( $find, ' ', $text );
597 $text = trim( $text );
598
599 return $text;
600 }
601
602 /**
603 * Check if a string is a valid datetime.
604 *
605 * @since 2.0.0
606 *
607 * @param string $datetime String input to check as valid input for DateTime class.
608 *
609 * @return bool
610 */
611 public static function is_valid_datetime( $datetime ) {
612 return YoastSEO()->helpers->date->is_valid_datetime( $datetime );
613 }
614
615 /**
616 * Format the URL to be sure it is okay for using as a redirect url.
617 *
618 * This method will parse the URL and combine them in one string.
619 *
620 * @since 2.3.0
621 *
622 * @param string $url URL string.
623 *
624 * @return mixed
625 */
626 public static function format_url( $url ) {
627 $parsed_url = wp_parse_url( $url );
628
629 $formatted_url = '';
630 if ( ! empty( $parsed_url['path'] ) ) {
631 $formatted_url = $parsed_url['path'];
632 }
633
634 // Prepend a slash if first char != slash.
635 if ( stripos( $formatted_url, '/' ) !== 0 ) {
636 $formatted_url = '/' . $formatted_url;
637 }
638
639 // Append 'query' string if it exists.
640 if ( ! empty( $parsed_url['query'] ) ) {
641 $formatted_url .= '?' . $parsed_url['query'];
642 }
643
644 return apply_filters( 'wpseo_format_admin_url', $formatted_url );
645 }
646
647 /**
648 * Retrieves the sitename.
649 *
650 * @since 3.0.0
651 *
652 * @return string
653 */
654 public static function get_site_name() {
655 return YoastSEO()->helpers->site->get_site_name();
656 }
657
658 /**
659 * Check if the current opened page is a Yoast SEO page.
660 *
661 * @since 3.0.0
662 *
663 * @return bool
664 */
665 public static function is_yoast_seo_page() {
666 return YoastSEO()->helpers->current_page->is_yoast_seo_page();
667 }
668
669 /**
670 * Check if the current opened page belongs to Yoast SEO Free.
671 *
672 * @since 3.3.0
673 *
674 * @param string $current_page The current page the user is on.
675 *
676 * @return bool
677 */
678 public static function is_yoast_seo_free_page( $current_page ) {
679 $yoast_seo_free_pages = [
680 'wpseo_tools',
681 'wpseo_search_console',
682 ];
683
684 return in_array( $current_page, $yoast_seo_free_pages, true );
685 }
686
687 /**
688 * Determine if Yoast SEO is in development mode?
689 *
690 * Inspired by JetPack (https://github.com/Automattic/jetpack/blob/master/class.jetpack.php#L1383-L1406).
691 *
692 * @since 3.0.0
693 *
694 * @return bool
695 */
696 public static function is_development_mode() {
697 $development_mode = false;
698
699 if ( defined( 'YOAST_ENVIRONMENT' ) && YOAST_ENVIRONMENT === 'development' ) {
700 $development_mode = true;
701 }
702 elseif ( defined( 'WPSEO_DEBUG' ) ) {
703 $development_mode = WPSEO_DEBUG;
704 }
705 elseif ( site_url() && strpos( site_url(), '.' ) === false ) {
706 $development_mode = true;
707 }
708
709 /**
710 * Filter the Yoast SEO development mode.
711 *
712 * @since 3.0
713 *
714 * @param bool $development_mode Is Yoast SEOs development mode active.
715 */
716 return apply_filters( 'yoast_seo_development_mode', $development_mode );
717 }
718
719 /**
720 * Retrieve home URL with proper trailing slash.
721 *
722 * @since 3.3.0
723 *
724 * @param string $path Path relative to home URL.
725 * @param string|null $scheme Scheme to apply.
726 *
727 * @return string Home URL with optional path, appropriately slashed if not.
728 */
729 public static function home_url( $path = '', $scheme = null ) {
730 return YoastSEO()->helpers->url->home( $path, $scheme );
731 }
732
733 /**
734 * Checks if the WP-REST-API is available.
735 *
736 * @since 3.6
737 * @since 3.7 Introduced the $minimum_version parameter.
738 *
739 * @param string $minimum_version The minimum version the API should be.
740 *
741 * @return bool Returns true if the API is available.
742 */
743 public static function is_api_available( $minimum_version = '2.0' ) {
744 return ( defined( 'REST_API_VERSION' )
745 && version_compare( REST_API_VERSION, $minimum_version, '>=' ) );
746 }
747
748 /**
749 * Determine whether or not the metabox should be displayed for a post type.
750 *
751 * @param string|null $post_type Optional. The post type to check the visibility of the metabox for.
752 *
753 * @return bool Whether or not the metabox should be displayed.
754 */
755 protected static function display_post_type_metabox( $post_type = null ) {
756 if ( ! isset( $post_type ) ) {
757 $post_type = get_post_type();
758 }
759
760 if ( ! isset( $post_type ) || ! WPSEO_Post_Type::is_post_type_accessible( $post_type ) ) {
761 return false;
762 }
763
764 if ( $post_type === 'attachment' && WPSEO_Options::get( 'disable-attachment' ) ) {
765 return false;
766 }
767
768 return apply_filters( 'wpseo_enable_editor_features_' . $post_type, WPSEO_Options::get( 'display-metabox-pt-' . $post_type ) );
769 }
770
771 /**
772 * Determine whether or not the metabox should be displayed for a taxonomy.
773 *
774 * @param string|null $taxonomy Optional. The post type to check the visibility of the metabox for.
775 *
776 * @return bool Whether or not the metabox should be displayed.
777 */
778 protected static function display_taxonomy_metabox( $taxonomy = null ) {
779 if ( ! isset( $taxonomy ) || ! in_array( $taxonomy, get_taxonomies( [ 'public' => true ], 'names' ), true ) ) {
780 return false;
781 }
782
783 return WPSEO_Options::get( 'display-metabox-tax-' . $taxonomy );
784 }
785
786 /**
787 * Determines whether the metabox is active for the given identifier and type.
788 *
789 * @param string $identifier The identifier to check for.
790 * @param string $type The type to check for.
791 *
792 * @return bool Whether or not the metabox is active.
793 */
794 public static function is_metabox_active( $identifier, $type ) {
795 if ( $type === 'post_type' ) {
796 return self::display_post_type_metabox( $identifier );
797 }
798
799 if ( $type === 'taxonomy' ) {
800 return self::display_taxonomy_metabox( $identifier );
801 }
802
803 return false;
804 }
805
806 /**
807 * Determines whether the plugin is active for the entire network.
808 *
809 * @return bool Whether the plugin is network-active.
810 */
811 public static function is_plugin_network_active() {
812 return YoastSEO()->helpers->url->is_plugin_network_active();
813 }
814
815 /**
816 * Gets the type of the current post.
817 *
818 * @return string The post type, or an empty string.
819 */
820 public static function get_post_type() {
821 $wp_screen = get_current_screen();
822
823 if ( $wp_screen !== null && ! empty( $wp_screen->post_type ) ) {
824 return $wp_screen->post_type;
825 }
826 return '';
827 }
828
829 /**
830 * Gets the type of the current page.
831 *
832 * @return string Returns 'post' if the current page is a post edit page. Taxonomy in other cases.
833 */
834 public static function get_page_type() {
835 global $pagenow;
836 if ( WPSEO_Metabox::is_post_edit( $pagenow ) ) {
837 return 'post';
838 }
839
840 return 'taxonomy';
841 }
842
843 /**
844 * Getter for the Adminl10n array. Applies the wpseo_admin_l10n filter.
845 *
846 * @return array The Adminl10n array.
847 */
848 public static function get_admin_l10n() {
849 $post_type = self::get_post_type();
850 $page_type = self::get_page_type();
851
852 $label_object = false;
853 $no_index = false;
854
855 if ( $page_type === 'post' ) {
856 $label_object = get_post_type_object( $post_type );
857 $no_index = WPSEO_Options::get( 'noindex-' . $post_type, false );
858 }
859 else {
860 $label_object = WPSEO_Taxonomy::get_labels();
861
862 $wp_screen = get_current_screen();
863
864 if ( $wp_screen !== null && ! empty( $wp_screen->taxonomy ) ) {
865 $taxonomy_slug = $wp_screen->taxonomy;
866 $no_index = WPSEO_Options::get( 'noindex-tax-' . $taxonomy_slug, false );
867 }
868 }
869
870 $wpseo_admin_l10n = [
871 'displayAdvancedTab' => WPSEO_Capability_Utils::current_user_can( 'wpseo_edit_advanced_metadata' ) || ! WPSEO_Options::get( 'disableadvanced_meta' ),
872 'noIndex' => (bool) $no_index,
873 'isPostType' => (bool) get_post_type(),
874 'postType' => get_post_type(),
875 'postTypeNamePlural' => ( $page_type === 'post' ) ? $label_object->label : $label_object->name,
876 'postTypeNameSingular' => ( $page_type === 'post' ) ? $label_object->labels->singular_name : $label_object->singular_name,
877 'isBreadcrumbsDisabled' => WPSEO_Options::get( 'breadcrumbs-enable', false ) !== true && ! current_theme_supports( 'yoast-seo-breadcrumbs' ),
878 'isAiFeatureActive' => (bool) WPSEO_Options::get( 'enable_ai_generator' ),
879 ];
880
881 $additional_entries = apply_filters( 'wpseo_admin_l10n', [] );
882 if ( is_array( $additional_entries ) ) {
883 $wpseo_admin_l10n = array_merge( $wpseo_admin_l10n, $additional_entries );
884 }
885
886 return $wpseo_admin_l10n;
887 }
888
889 /**
890 * Retrieves the analysis worker log level. Defaults to errors only.
891 *
892 * Uses bool YOAST_SEO_DEBUG as flag to enable logging. Off equals ERROR.
893 * Uses string YOAST_SEO_DEBUG_ANALYSIS_WORKER as log level for the Analysis
894 * Worker. Defaults to INFO.
895 * Can be: TRACE, DEBUG, INFO, WARN or ERROR.
896 *
897 * @return string The log level to use.
898 */
899 public static function get_analysis_worker_log_level() {
900 if ( defined( 'YOAST_SEO_DEBUG' ) && YOAST_SEO_DEBUG ) {
901 return defined( 'YOAST_SEO_DEBUG_ANALYSIS_WORKER' ) ? YOAST_SEO_DEBUG_ANALYSIS_WORKER : 'INFO';
902 }
903
904 return 'ERROR';
905 }
906
907 /**
908 * Returns the unfiltered home URL.
909 *
910 * In case WPML is installed, returns the original home_url and not the WPML version.
911 * In case of a multisite setup we return the network_home_url.
912 *
913 * @codeCoverageIgnore
914 *
915 * @return string The home url.
916 */
917 public static function get_home_url() {
918 return YoastSEO()->helpers->url->network_safe_home_url();
919 }
920
921 /**
922 * Prepares data for outputting as JSON.
923 *
924 * @param array $data The data to format.
925 *
926 * @return string|false The prepared JSON string.
927 */
928 public static function format_json_encode( $data ) {
929 $flags = JSON_UNESCAPED_UNICODE;
930
931 if ( self::is_development_mode() ) {
932 $flags = ( $flags | JSON_PRETTY_PRINT );
933
934 /**
935 * Filter the Yoast SEO development mode.
936 *
937 * @param array $data Allows filtering of the JSON data for debug purposes.
938 */
939 $data = apply_filters( 'wpseo_debug_json_data', $data );
940 }
941
942 // phpcs:ignore Yoast.Yoast.JsonEncodeAlternative.FoundWithAdditionalParams -- This is the definition of format_json_encode.
943 return wp_json_encode( $data, $flags );
944 }
945
946 /**
947 * Extends the allowed post tags with accessibility-related attributes.
948 *
949 * @codeCoverageIgnore
950 *
951 * @param array $allowed_post_tags The allowed post tags.
952 *
953 * @return array The allowed tags including post tags, input tags and select tags.
954 */
955 public static function extend_kses_post_with_a11y( $allowed_post_tags ) {
956 static $a11y_tags;
957
958 if ( isset( $a11y_tags ) === false ) {
959 $a11y_tags = [
960 'button' => [
961 'aria-expanded' => true,
962 'aria-controls' => true,
963 ],
964 'div' => [
965 'tabindex' => true,
966 ],
967 // Below are attributes that are needed for backwards compatibility (WP < 5.1).
968 'span' => [
969 'aria-hidden' => true,
970 ],
971 'input' => [
972 'aria-describedby' => true,
973 ],
974 'select' => [
975 'aria-describedby' => true,
976 ],
977 'textarea' => [
978 'aria-describedby' => true,
979 ],
980 ];
981
982 // Add the global allowed attributes to each html element.
983 $a11y_tags = array_map( '_wp_add_global_attributes', $a11y_tags );
984 }
985
986 return array_merge_recursive( $allowed_post_tags, $a11y_tags );
987 }
988
989 /**
990 * Extends the allowed post tags with input, select and option tags.
991 *
992 * @codeCoverageIgnore
993 *
994 * @param array $allowed_post_tags The allowed post tags.
995 *
996 * @return array The allowed tags including post tags, input tags, select tags and option tags.
997 */
998 public static function extend_kses_post_with_forms( $allowed_post_tags ) {
999 static $input_tags;
1000
1001 if ( isset( $input_tags ) === false ) {
1002 $input_tags = [
1003 'input' => [
1004 'accept' => true,
1005 'accesskey' => true,
1006 'align' => true,
1007 'alt' => true,
1008 'autocomplete' => true,
1009 'autofocus' => true,
1010 'checked' => true,
1011 'contenteditable' => true,
1012 'dirname' => true,
1013 'disabled' => true,
1014 'draggable' => true,
1015 'dropzone' => true,
1016 'form' => true,
1017 'formaction' => true,
1018 'formenctype' => true,
1019 'formmethod' => true,
1020 'formnovalidate' => true,
1021 'formtarget' => true,
1022 'height' => true,
1023 'hidden' => true,
1024 'lang' => true,
1025 'list' => true,
1026 'max' => true,
1027 'maxlength' => true,
1028 'min' => true,
1029 'multiple' => true,
1030 'name' => true,
1031 'pattern' => true,
1032 'placeholder' => true,
1033 'readonly' => true,
1034 'required' => true,
1035 'size' => true,
1036 'spellcheck' => true,
1037 'src' => true,
1038 'step' => true,
1039 'tabindex' => true,
1040 'translate' => true,
1041 'type' => true,
1042 'value' => true,
1043 'width' => true,
1044
1045 /*
1046 * Below are attributes that are needed for backwards compatibility (WP < 5.1).
1047 * They are used for the social media image in the metabox.
1048 * These can be removed once we move to the React versions of the social previews.
1049 */
1050 'data-target' => true,
1051 'data-target-id' => true,
1052 ],
1053 'select' => [
1054 'accesskey' => true,
1055 'autofocus' => true,
1056 'contenteditable' => true,
1057 'disabled' => true,
1058 'draggable' => true,
1059 'dropzone' => true,
1060 'form' => true,
1061 'hidden' => true,
1062 'lang' => true,
1063 'multiple' => true,
1064 'name' => true,
1065 'onblur' => true,
1066 'onchange' => true,
1067 'oncontextmenu' => true,
1068 'onfocus' => true,
1069 'oninput' => true,
1070 'oninvalid' => true,
1071 'onreset' => true,
1072 'onsearch' => true,
1073 'onselect' => true,
1074 'onsubmit' => true,
1075 'required' => true,
1076 'size' => true,
1077 'spellcheck' => true,
1078 'tabindex' => true,
1079 'translate' => true,
1080 ],
1081 'option' => [
1082 'class' => true,
1083 'disabled' => true,
1084 'id' => true,
1085 'label' => true,
1086 'selected' => true,
1087 'value' => true,
1088 ],
1089 ];
1090
1091 // Add the global allowed attributes to each html element.
1092 $input_tags = array_map( '_wp_add_global_attributes', $input_tags );
1093 }
1094
1095 return array_merge_recursive( $allowed_post_tags, $input_tags );
1096 }
1097
1098 /**
1099 * Gets an array of enabled features.
1100 *
1101 * @return string[] The array of enabled features.
1102 */
1103 public static function retrieve_enabled_features() {
1104 /**
1105 * The feature flag integration.
1106 *
1107 * @var Feature_Flag_Integration $feature_flag_integration
1108 */
1109 $feature_flag_integration = YoastSEO()->classes->get( Feature_Flag_Integration::class );
1110 return $feature_flag_integration->get_enabled_features();
1111 }
1112 }
1113